装饰模式
原理
动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活!
结构图
Component职责抽象类
/// <summary>
/// 管理增加职责抽象类
/// </summary>
public abstract class Component
{
public abstract void Operation();
}
抽象ConcreteComonent类
public class ConcreteComonent : Component
{
public override void Operation()
{
Debug.Log("具体对象的操作");
}
}
抽象Decorator装饰类
public abstract class Decorator :Component
{
protected Component component;
public void SetCompoent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
ConcreteDecoratorA具体装饰实现类
public class ConcreteDecoratorA : Decorator
{
private string addedState;
public override void Operation()
{
base.Operation();
addedState = "new state";
Debug.Log("对象A的具体操作");
}
}
ConcreteDecoratorB具体装饰实现类
public class ConcreteDecoratorB : Decorator
{
private string addedState;
public override void Operation()
{
base.Operation();
addedState = "new state";
Debug.Log("对象B的具体操作");
}
}
最终实现
public class Hello
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Main()
{
//CashContext cashContext = new CashContext("打五折");
//cashContext.GetResult();
ConcreteComonent c = new ConcreteComonent();
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA();
ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB();
concreteDecoratorA.SetCompoent(c);
concreteDecoratorB.SetCompoent(concreteDecoratorA);
concreteDecoratorB.Operation();
}
}
小结
装饰模式是利用SetComponent来对对象进行包装的,这样每个装饰对象的实现就和如何使用这个对象分离开了,每个对象只关心自己的功能,不需要关心如何被添加到对象链中!