** 设计模式 c# ** ** 语言描述——装饰( Decorator ** ** )模式 **
- 本文参考了《 JAVA 与模式》的部分内容,适合于设计模式的初学者。
装饰模式又名包装模式,以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。它使用原来被装饰的类的一个子类的实例,把客户端的调用委派到被装饰类,客户端并不会觉得对象在装饰前和装饰后有什么不同。在以下情况下应使用装饰模式:需要扩展一个类的功能,或给一个类增加附加责任。动态地给一个对象增加功能,这些功能可以再动态地撤销。需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。
类图如下所示:
装饰模式包括如下角色:
抽象构件( Component ):给出一个抽象接口,以规范准备接收附加责任的对象。
具体构件( Concrete Component ):定义一个将要接收附加责任的类。
装饰( Decorator ):持有一个构件对象的实例,并定义一个与抽象构件接口一致的接口。
具体装饰( Concrete Decorator ):负责给构件对象“贴上”附加的责任。
** Component: **
public interface Component
{
void sampleOperation();
} // END INTERFACE DEFINITION Component
** Decorator: **
public class Decorator : Component
{
private Component component;
public Decorator(Component component)
{
this .component=component;
}
public virtual void sampleOperation()
{
component.sampleOperation();
}
} // END CLASS DEFINITION Decorator
** ConcreteComponent: **
public class ConcreteComponent : Component
{
public void sampleOperation()
{
Console.WriteLine ("ConcreteComponent sampleOperation");
}
} // END CLASS DEFINITION ConcreteComponent
** ConcreteDecorator1: **
public class ConcreteDecorator1 : Decorator
{
public ConcreteDecorator1(Component component): base (component)
{
}
override public void sampleOperation()
{
base .sampleOperation ();
Console.WriteLine ("ConcreteDecorator1 sampleOperation");
}
} // END CLASS DEFINITION ConcreteDecorator1
** ConcreteDecorator2: **
public class ConcreteDecorator2 : Decorator
{
public ConcreteDecorator2 (Component component): base (component)
{
}
override public void sampleOperation()
{
base .sampleOperation ();
Console.WriteLine ("ConcreteDecorator2 sampleOperation");
}
} // END CLASS DEFINITION ConcreteDecorator2
** Client: **
static void Main ( string [] args)
{
Component component= new ConcreteComponent ();
Component concretedecorator1= new ConcreteDecorator1 (component); // 包装
Component concretedecorator2= new ConcreteDecorator2 (concretedecorator1);
concretedecorator2.sampleOperation ();
}
程序输出如下:
ConcreteComponent sampleOperation
ConcreteDecorator1 sampleOperation
ConcreteDecorator2 sampleOperation