装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

Component是定义一个对象的接口,可以给这些对象动态地添加职责,ContreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator ,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的,至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职现的功能[DPE]。

Component 类
abstrat class Component
{
public abstract void Operation();
}class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}abstract class Decorator : Component
{
protected Component component; public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if(component != null)
{
component.Operation();
}
}
}class ConcreteDecoratorA : Decorator
{
private string addedState; public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
class ConcreteDecoratorB : Decorator
{
private string addedState; public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("具体装饰对象B的操作");
}
//本类独有的方法,以区别于 ConcreteDecoratorA
private void AddedBehavior()
{ }
}---客户端代码 ---
static void Main(string[] args)
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d1 = new ConcreteDecoratorB(); d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation(); Console.Read();
}

装饰模式利用SetComponent 来对对象进行包装的,这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链中。

 图:

装饰模式_抽象类