装饰者模式
装饰者模式动态的给对象赋予新的职责,无需修改原始对象。
要区分装饰者对象和被装饰的“组件之间的区别。
装饰者对象和被装饰的组件都继承同一个超类,表明它们属于同一个类型。
装饰者对象携带着新的职责(方法),以组合的方式包含被装饰的组件对象,就可以让组件可以使用该新的功能。

代码示例:
1 package Decoration; 2 /** 3 * 抽象组件基类,具体组件类和装饰器类都继承它 4 * @author TisaKong 5 * 2015-7-29 6 */ 7 public abstract class Component { 8 public void doStuffA(){ 9 System.out.println(this.getClass().getSimpleName()); 10 } 11 12 abstract public void doStuffB(); 13 }
1 package Decoration; 2 /** 3 *具体的组件类 4 */ 5 public class ConcreteComponent extends Component { 6 7 @Override 8 public void doStuffB() { 9 System.out.println("ConcreteCompo, do what I wanna do"); 10 } 11 12 }
1 package Decoration; 2 3 /** 4 *装饰者基类 5 */ 6 public class Decorator extends Component { 7 8 @Override 9 public void doStuffB() { 10 System.out.println("Decorator, do something new"); 11 } 12 13 //new duty to do 14 15 public void newStuff(){ 16 System.out.println("my children can rewrite me :newStuff"); 17 } 18 19 public void newStuffB(){ 20 System.out.println("my children can rewrite me :newStuffB"); 21 } 22 23 }
1 package Decoration; 2 /** 3 * 具体的装饰者类,扩展新的功能 4 */ 5 public class ConcreteDecoratorA extends Decorator { 6 Component comp; 7 8 public ConcreteDecoratorA(Component comp) { 9 this.comp = comp; 10 } 11 12 @Override 13 public void newStuff() { 14 super.newStuff(); 15 System.out.println("haha , I rewrite you "); 16 } 17 18 @Override 19 public void newStuffB() { 20 super.newStuffB(); 21 System.out.println("yes I reWrite you , cA"); 22 } 23 }
1 package Decoration; 2 3 public class Client { 4 public static void main(String[] args) { 5 Decorator de = new ConcreteDecoratorA(new ConcreteComponent()); 6 de.doStuffA(); 7 de.doStuffB(); 8 /*赋予组件新的职责*/ 9 de.newStuff(); 10 de.newStuffB(); 11 } 12 }
输出结果:
ConcreteDecoratorA Decorator, do something new my children can rewrite me :newStuff haha , I rewrite you my children can rewrite me :newStuffB yes I reWrite you , cA

浙公网安备 33010602011771号