裝飾模式(Decorator):動態地給一個對象添加一些額外的職責,就增加功能來說,裝飾模式比生成子類更為靈活。
namespace Decorator { public abstract class Component { public abstract void Operation(); } public class ConcreteComponent:Component { public override void Operation() { Console.WriteLine("具體對象的操作"); } } public abstract class Decorator:Component { protected Component component; public void SetComponent(Component component) { this.component = component; } public override void Operation() { if(component!=null) { component.Operation(); } } } public class ConcreteDecoratorA:Decorator { private string addedState; public override void Operation() { base.Operation(); addedState = "New State"; Console.WriteLine("具體裝飾對象A的操作"); } } public class ConcreteDecoratorB : Decorator { public override void Operation() { base.Operation(); AddedBehavior(); Console.WriteLine("具體裝飾對象B的操作"); } private void AddedBehavior() { } } }View Code
測試代碼:
ConcreteComponent c = new ConcreteComponent(); ConcreteDecoratorA d1 = new ConcreteDecoratorA(); ConcreteDecoratorB d2 = new ConcreteDecoratorB(); d1.SetComponent(c); d2.SetComponent(d1); d2.Operation();