装饰模式

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

clip_image002

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

Component类

Abstract class Component

{

Public abstract void Operation();

}

ConcreteComponent类

Class ConcreteComponent:Component

{

Public override void Operation()

{

Console.WriteLine(“具体的操作对象”);

}

}

Decorator类

Abstract class Decorator:Component

{

Protected Component component;

Public void SetComponent(Component component)//设置Component

{

This.component = component;

}

//重写Operation(),实际执行的是Component的Operation()

Public override void Operation()

{

If(this.component !=null)

{

This.component.Operation();

}

}

}

ConcreteDecorationA类

Class ConcreteDecoratorA:Decorator

{
private string addedState;//本类的独有功能,以区别于ConcreteDecoratorB

Public override void Operation()//首先运行原Component的Operation(),再执行本类的功能,如addedState,相关于对原Component进行了装饰

{

Base.Operation();

addedState = “New State”;

Console.WriteLine(“具体装饰对象A的操作”);

}

}

Class ConcreteDecoratorB:Decorator

{

Public override void Operation()

{

Base.Operation();//首先运行原Component的Operation(),再执行本类的功能,如AddedBehavior(),相当于对原Component进行了装饰

AddBehavior();

Console.WriteLine(“具体装饰对象B的操作”);

}

Private void AddedBehavior()本类独有的方法,以区别到ConcreteComponentA

{

}

}

客户端代码

Static void Main(string[] args)\

{

ConcreteComponent c = new ConcreteComponent();

ConcreteDecoratorA d1 = new ConcreteDecoratorA();

ConcreteDecoratorB d2 = new ConcreteDecoratorB();

d1. SetComponent(c);

d2. SetComponent(d1);

d2.Show();

}

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

如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类。同样的道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。

装饰模式是为已有功能动态地添加更多功能的一种方式。

当系统需要新功能的时侯,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为,但这种做法的问题在于,它们在主类中加入新的字段,新的方法,和新的逻辑,从而增加了主类的复杂度,而这些新加入的东西仅仅是为了满足一些只在某种特定情况下才会执行的特殊行的需要。而装饰模饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象。因此,当需要执行特殊为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。

posted @ 2011-10-21 21:49  晓炜  阅读(188)  评论(0)    收藏  举报