装饰者模式:动态的给一个对象添加一些额外的职责。就增加功能来说,装饰模式比生成子类更灵活!
当系统需要更新内容的时候,可能需要向旧的类中添加新的方法,这些新加的代码通常装饰了原有类的核心职责或行为。再主类中添加新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行为的需要。装饰者模式可以将每个需要装饰的功能单独的放在一个类中,并让这个类包装它所需要装饰的对象。当需要执行特殊行为时,客户端代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { abstract class Component { public abstract void Operation(); } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { class ConcreteComponent:Component { public override void Operation() { Console.Write("具体的操作!"); } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { abstract class Decorator : Component { protected Component component; public void SetComponent(Component component) {//设置component this.component = component; } public override void Operation()//重写Operation,实际执行的是Component的Operation() { if (component != null) { component.Operation();//虽然继承了一个抽象类Component,但这个抽象类有一个子类ConcreteComponent, } //这个子类中有一个可以被调用的operation方法 } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { class ConcreateDecoratorA:Decorator { private string addedState; public override void Operation() { base.Operation();//首先运行原Component的Operation(),再执行本类的的功能,如addedState,相当于对原Component进行了封装 addedState = "New State"; Console.Write("具体的装饰对象A的操作!"); } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { class ConcreateDecoratorB:Decorator { public override void Operation() { base.Operation();//先运行父类方法,Operation, AddedBehavior();//再运行本类要做的事情。 Console.Write("具体装饰对象B的操作!"); } private void AddedBehavior() { //do sth…… } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Decorator { class Program { static void Main(string[] args) { ConcreteComponent c = new ConcreteComponent(); ConcreateDecoratorA d1 = new ConcreateDecoratorA(); ConcreateDecoratorB d2 = new ConcreateDecoratorB(); d1.SetComponent(c); d2.SetComponent(d1); d2.Operation();//concreteComponent中的Operation的事做了。D1中的方法也运行了。D2中的方法也做了! Console.ReadKey(); } } }