I'm having a hard time implementing a simple composition example in Java:
Java Code:
public class CompositionPattern {
public static void main(String[] args) {
Udp udp = new Udp();
Imap imap = new Imap();
udp.startService();
imap.startService();
}
}
public class Imap {
private Responder responder;
public Imap(){
this.responder = new Responder(this);
}
public void startService(){
responder.doStuff();
}
public boolean supportsMe(){
return true;
}
}
public class Udp {
private Responder responder;
public Udp(){
this.responder = new Responder(this);
}
public void startService(){
responder.doStuff();
}
public boolean supportsMe(){
return false;
}
}
public class Responder {
Object parent;
public Responder(Object parent){
this.parent = parent;
}
public void doStuff(){
if(parent.supportsMe()){
System.out.println("Parent supports me.");
} else {
System.out.println("Parent doesn't support me.");
}
}
}
The above won't compile. It says "The method supportsMe() is undefined for the type Object". I understand that I stored parent as an Object. But in reality it is not simply Object, but a Udp object or Imap object. The point is to make Responder generic. I don't want to have to cast the Object to Udp or Imap. Any solutions so I can keep this generic?
No comments:
Post a Comment