装饰模式(Decorator Pattern):指在不必改变原类文件和使用继承的情况下动态的扩展一个对象的功能。简单一点说,装饰模式就是动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式要比生成子类更为灵活。
装饰模式结构图:
装饰模式基本代码:
1.Component类
//Component类
abstract class Component
{
public abstract void Operation();
}
2.ConcreteComponent类
//ConcreteComponent类
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine ("具体对象的操作");
}
}
3.Decorator类
//Decorator类
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Componentcomponent)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
4.ConcreteDecoratorA类
//ConcreteDecoratorA类
class ConcreteDecoratorA : Decorator
{
private string AddedState;
public override void Operation()
{
base.Operation(); //首先运行原Compnent的Operation(),再执行本类的功能,如AddedBehavior,相当于对原Component进行了装饰
AddedState ="New State"; //本类独有的方法,以区别于ConcreteDecoratorA
Console.WriteLine("具体装饰对象A的操作");
}
}
5.客户端代码
//客户端代码
static void Main(string[] args)
{
ConcreteComponent c = newConcreteComponent();
ConcreteDecoratorA d1 = newConcreteDecoratorA();
d1.SetComponent(c); //装饰的方法是:首先用ConcreteComponent实例化对象c,然后用ConcreteDecoratorA的实例化对象d1来包装c,最终执行d1的Operation()
d2.Operation();
Console.Read();
}
装饰模式的基本代码架构很简单,可是其中具体细节的逻辑关系,还需要读者细细品味了。
通过以上代码,我们可以发现,装饰模式就是利用SetComponent来对对象进行包装的。这样对象的装饰和对象的使用就分离开了。
这就是装饰模式的优点所在,把类中的装饰功能从类中搬移去除,这样,不仅简化了原来的泪,而且可以去除相关类中重复的逻辑。