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來對對象進行包裝,每一個裝飾對象的實現就和如何使用這個對象分離開了,每一個裝飾對象只關心本身的功能,不須要關心如何被添加到對象鏈當中。