设计模式——装饰模式
装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活
abstract class Component
{
public abstract void Operation();
}
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
//装饰类
abstract class Decorator : Component
{
protected Component component;
//设置Component
public void SetComponent(Component component)
{
this.component = component;
}
//重写Operation(),实际执行的是Component 的Operation()
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
class ConcreteDecoratorA : Decorator
{
private string addedState; //本类的独有功能,以区别于ConcreteDecoratorB
public override void Operation()
{
base.Operation();//首先运行原Component的Operation(),再执行本类的功能,如addedState,相当于对原Component进行装饰
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();//首先运行原Component的Operation(),再执行本类的功能,如addedState,相当于对原Component进行装饰
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}
private void AddedBehavior()本类的独有功能,以区别于ConcreteDecoratorA
{
Console.WriteLine("ConcreteDecoratorB");
}
}
static void Main(string[] args)
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
//装饰的方法是:首先用ConcreteComponent实例化对象c
//,然后用ConcreteDecoratorA的实例化对象d1来包装c,
//再用ConcreteDecoratorB的对象d2包装d1,最终执行d2的d2.Operation()
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
}