定义
Decorator设计模式动态地将额外的责任附加到对象上。此模式提供了比继承更有弹性的替代方法。
OO设计原则
对扩展开放,对修改关闭。
类图
装饰者模型类图
代码
Component.cs
namespace DesignPattern.Decorator.Structural
{
public abstract class Component
{
public abstract void Operation();
}
}
ConcreteComponent.cs
namespace DesignPattern.Decorator.Structural
{
public class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("ConcreteComponent Operation.");
}
}
}
Decorator.cs
namespace DesignPattern.Decorator.Structural
{
public abstract class Decorator : Component
{
protected Component? component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component != null)
{
component.Operation();
}
}
}
}
ConcreteDecoratorA.cs
namespace DesignPattern.Decorator.Structural
{
public class ConcreteDecoratorA : Decorator
{
public override void Operation()
{
base.Operation();
Console.WriteLine("ConcreteDecoratorA Operation.");
}
}
}
ConcreteDecoratorB.cs
namespace DesignPattern.Decorator.Structural
{
public class ConcreteDecoratorB : Decorator
{
public override void Operation()
{
base.Operation();
Console.WriteLine("ConcreteDecoratorB Operation.");
AddedBehavior();
}
private void AddedBehavior()
{
Console.WriteLine("ConcreteDecoratorB Added Behavior.");
}
}
}
Program.cs
using DesignPattern.Decorator.Structural;
internal class Program
{
private static void Main(string[] args)
{
ConcreteComponent concreteComponent = new ConcreteComponent();
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA();
ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB();
concreteDecoratorA.SetComponent(concreteComponent);
concreteDecoratorB.SetComponent(concreteDecoratorA);
concreteDecoratorB.Operation();
}
}