装饰者模式
装饰者模式:动态地给一个对象添加一些额外的职责,就增加功能来说,Decorator模式比生成子类更为灵活。
Decorator模式的工作原理是:可以创建始于Decorator对象(负责新的功能的对象)终于原对象的一个对象“链”。
适用性
在以下情况下可以使用 Decorator 模式:
- 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
- 处理那些可以撤销的职责。
- 当不能采用生成子类的方法进行扩充时。
- Decorator 是一个透明的包装,其与 Component 还是有些差别的。
- 采用 Decorator 模式进行系统设计往往会产生许多看上去类似的小对象。导致很难学习系统,排错也很困难。
- 比静态继承更灵活。
- 避免在层次结构高层的类有太多的特征。
结构

例:
class Program
{
static void Main(string[] args)
{
Car car=new Car();
car.Operation();
ComponentA componentA = new ComponentA(car);
componentA.Operation();
Console.WriteLine("\r\n");
Truck truck = new Truck();
truck.Operation();
ComponentB componentB=new ComponentB(truck);
componentB.Operation();
Console.ReadKey();
}
public class Car : Component
{
public override void Operation()
{
Console.WriteLine("我是普通的轿车,速度90km/h!\r\n");
}
}
public class Truck:Component
{
public override void Operation()
{
Console.WriteLine("我是普通的卡车,速度50km/h!\r\n");
}
}
public abstract class Component
{
public abstract void Operation();
}
public class ComponentA : Component
{
private Component _component;
public ComponentA(Component component)
{
this._component = component;
}
public override void Operation()
{
this._component.Operation();
AddNewEngine();
Console.WriteLine("增加了液氮推进器,速度狂飙到200km/h!\r\n");
}
public void AddNewEngine()
{
Console.Write("增加液氮推进器!\r\n");
}
}
public class ComponentB:Component
{
private Component _component;
public ComponentB(Component component)
{
_component = component;
}
public override void Operation()
{
_component.Operation();
AddNewEngine();
Console.WriteLine("增加了火箭推进器,速度狂飙到300km/h!\r\n");
}
public void AddNewEngine()
{
Console.WriteLine("增加火箭推进器!\r\n");
}
}
}
运行结果:

浙公网安备 33010602011771号