The following is a simplification from a project I am working on.
We have Talker niceTalker
who says "Good morning! My name is Joe". Then we have a schitzophrenic rudeTalker
, who says "He is me".
It took me a while to understand what the code does. To me, this seems an awfully complicated way of overriding Talker
s talk()
method. Furher more, TalkModifier
is used as a command in Command pattern (not shown).
Why take this approach, instead of say polymorphism through inheritance? Is this a known pattern, which one?
public interface Talker {
String getName();
void talk();
}
-
public interface TalkModifier {
public Talker modify(Talker talker);
}
-
class NiceGuy implements Talker {
@Override
public void talk() {
System.out.println("Good morning! My name is " + getName() +".");
}
@Override
public String getName() {
return "Joe";
}
}
public class Application {
public static void main(String[] args) {
Talker niceTalker = new NiceGuy();
TalkModifier rudeTalker = new TalkModifier() {
public Talker modify(final Talker talker) {
return new Talker() {
@Override
public void talk() {
System.out.println("He is me.");
}
@Override
public String getName() {
return talker.getName();
}
};
}
};
niceTalker.talk();
System.out.println();
rudeTalker.modify(niceTalker).talk();
}
}
Aucun commentaire:
Enregistrer un commentaire