标签:blog http 使用 strong io 2014
装饰者模式:动态地给一个对象添加一些额外的职责,就增加功能来说,Decorator模式比生成子类更为灵活。
Decorator模式的工作原理是:可以创建始于Decorator对象(负责新的功能的对象)终于原对象的一个对象“链”。
适用性
在以下情况下可以使用 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");
}
}
}
运行结果:

标签:blog http 使用 strong io 2014
原文地址:http://www.cnblogs.com/superCow/p/3848702.html