The following is a simplification from the project I'm working on.
We have one Talker niceTalkerthat says, "Good morning! My name is Joe." Then we have a schizophrenic rudeTalkerwho says, "He is me."
It took me a while to figure out what the code is doing. For me, this seems like a very complicated way to override a method Talker talk(). Moreover, it is TalkModifierused as a command in the Command Template (not shown).
Why use this approach rather than polymorphism through inheritance? This is a famous template, 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();
}
}