动态地给一个对象添加一些额外的职责。就增加功能来说,D e c o r a t o r 模式相比生成子类更为灵活。
比如:一个坏男孩为了相亲时迎合不同女孩的需要,必须经常变换自己的喜好,今天要变成一个喜欢说法语的人,明天又要变成即喜欢玩球,又喜欢说英语的人,后天要变成即喜欢说法语,又喜欢说英语的人,他必须能灵活应变。
abstract class BadBoy{
public void beBf(String str){
System.out.println("I can be your Bad boyfriend.");
}
}
class SpeakEnglish extends BadBoy{
public void beBf(String str){
System.out.println("I can be your English boyfriend "+str);
}
}
abstract class Decorator extends BadBoy{
BadBoy badboy;
public Decorator(BadBoy badboy) {
this.badboy = badboy;
}
}
class PlayBall extends Decorator {
public PlayBall(BadBoy badboy) {
super(badboy);
}
public void beBf(String str){
badboy.beBf(str);
playBall();
}
public void playBall(){
System.out.println("I can play ball very well.");
}
}
class SpeakFrench extends Decorator{
public SpeakFrench(BadBoy badboy) {
super(badboy);
}
public void beBf(String str){
badboy.beBf(str);
speakFrench();
}
public void speakFrench(){
System.out.println("I can speak French very well.");
}
}
public class DecorateBoy extends BadBoy{
public static void main(String[] args){
BadBoy boya = new PlayBall(new SpeakFrench(new SpeakEnglish()));
boya.beBf("Mary");
}
}
这样,这个男孩就可以灵活应对不同的需求了。