装饰模式:
为已有功能动态的添加更多的功能。
如果没有抽象实体,装饰类直接继承实体。
如果只有一个装饰实体,可以将装饰实体与抽象装饰类合并。???
装饰类:
//装饰类
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
装饰实体:
//实体
class ConcreteDecoratorA : Decorator
{
private string addedState;
public override void Operation()
{
//运行基类的Operation方法,再执行本类功能
//相当于对原类Component进行了装饰
base.Operation();
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}
public void AddedBehavior()
{
//本类独有的方法
Console.WriteLine("B独有的方法");
}
}
装饰类所装饰的实体:
//抽象类,Component(组成,部件元件)
abstract class Component
{
//(操作)
public abstract void Operation();
}
//实体
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
使用:
ConcreteComponentc = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.Operation();
d2.Operation();
Console.WriteLine();
d1.SetComponent(d2);
d1.Operation();