裝飾模式
裝飾模式:動態(tài)的給一個對象添加一些額外的職責(zé),就增加功能來說,裝飾模式比生成子類更加靈活。
Component定義一個對象接口,可以給這些對象動態(tài)的添加職責(zé)。
ConcreteComponent是定義了一個具體的對象,也可以給這個對象添加一些職責(zé)。
Decorator,裝飾抽象類,繼承了Component,從外類來擴展Component類的功能,但對于Component來說,是無需知道Decorator的存在。
ConcreteDecoratorA和ConcreteDecoratorB是具體裝飾對象,起到給Component添加職責(zé)的功能。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | abstract class Component{ public abstract void Operation(); } class ConcreteComponent extend Component{ public Operation(){ console.log(“具體對象操作”); } } abstract class Decorator extend Component{ protected Component component; public setComponent(Component component){ this .component = component; } public Operation(){ if ( this .component != null ){ component.Operation(); } } } class ConcreteDecoratorA extend Decorator{ private string addedState; public Operation(){ super .Operation(); addedState = "new State" ; console.log( "具體裝飾對象A操作" ); } } class ConcreteDecoratorB extend Decorator{ public Operation(){ super .Operation(); addedBehavior(); console.log( "裝飾對象B的操作" ); } private addedBehavior(){} } class Main{ ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.setComponent(c); d2.setComponent(d1); d2.Operation(); } |
該模式利用setComponent來對對象進行包裝,每個裝飾對象的實現(xiàn)就和如何使用這個對象分離開了,每個裝飾對象只關(guān)心自己的功能,不需要關(guān)心如何被添加到對象鏈當中。
http://www.cnblogs.com/xiaohaoxuezhang/p/6768432.html