装饰器模式
public class Competitor { public void sing() { System.out.println("我唱唱唱......"); } }
public class CompetitorDecorator1 extends Competitor { public void sing() { this.dance(); super.sing(); } private void dance() { System.out.println("偏偏起舞...."); } }
public class CompetitorDecorator2 extends Competitor { public void sing() { this.playMusic(); super.sing(); } private void playMusic() { System.out.println("播放背景音乐......"); } }
publicclass CompetitorDecorator3 extends Competitor { public void sing() { super.sing(); this.introduceBackground(); } private void introduceBackground() { System.out.println("悲惨背景介绍,博取同情,赢感情牌...."); } }
是的,这样确实可以完成相应的功能。但是有没有觉得怪怪的呢?
1.我们在CompetitorDecorator2内已经有了 playMusic() 代码片段,我们在CompetitorDecorator4内有和它完全一样的playMusic()代码片段,这个是不合适的,也是不可取的!
2.如果这个选手比较有才,有五花八门的各种装饰,我们为此要增加相应多的装饰类;如果他在这方面有很深的造诣,把这些装饰发挥的淋漓尽致,能把这些装饰融合到一块,这些五花八门的装饰随机组合,这得要衍生多少个子类啊!!!!!
我们一般性地算一下,如果有不同的装饰功能 N 个,那么,如果我们将这N个随机组合,将有:
也就是说做多可以产生sum 个子类,相信学过排列组合的人知道这是个什么概念,另外有多么庞大的代码重复……
装饰器
public class CompetitorDecorator extends Competitor{ private Competitor competitor; public CompetitorDecorator(Competitor competitor) { this.competitor= competitor; } public void sing() { competitor.sing(); } }
public class CompetitorDecoratorA extends CompetitorDecorator { public CompetitorDecoratorA(Competitor competitor) { super(competitor); } public void sing() { this.dance(); super.sing(); } private void dance() { System.out.println("偏偏起舞...."); } } ————————————————
public class CompetitorDecoratorB extends CompetitorDecorator { public CompetitorDecoratorB(Competitor competitor) { super(competitor); } public void sing() { this.playMusic(); super.sing(); } private void playMusic() { System.out.println("播放背景音乐......"); } } ————————————————
public class CompetitorDecoratorC extends CompetitorDecorator { public CompetitorDecoratorC(Competitor competitor) { super(competitor); } publi cvoid sing() { super.sing(); this.introduceBackground(); } private void introduceBackground() { System.out.println("悲惨背景介绍,博取同情,赢感情牌...."); } }
public class Client { public static void main(String[] args) { Competitor com = new Competitor(); // 加入了跳舞修饰,decorator 的sing() 方法中被动态添加了dance 修饰 CompetitorDecorator decorator = new CompetitorDecoratorA(com); // 在上面修饰的基础上,加入背景音乐修饰 decorator = new CompetitorDecoratorB(decorator); // 在上面修饰的基础上,加上悲惨的身世介绍 decorator = new CompetitorDecoratorC(decorator); decorator.sing(); System.out.println("满场尖叫,满分通过!!!!!"); } }