装饰器模式动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。
// 组件接口
public interface IComponent
{ void Operation();
} // 具体组件
public class ConcreteComponent : IComponent
{ public void Operation() { Console.WriteLine("ConcreteComponent.Operation()"); }
} // 装饰器抽象类
public abstract class Decorator : IComponent
{ protected IComponent _component; public Decorator(IComponent component) { _component = component; } public virtual void Operation() { _component.Operation(); }
} // 具体装饰器
public class ConcreteDecoratorA : Decorator
{ public ConcreteDecoratorA(IComponent component) : base(component) {} public override void Operation() { base.Operation(); AddedFunctionality(); } private void AddedFunctionality() { Console.WriteLine("Added functionality in ConcreteDecoratorA"); }
} // 客户端代码
class Program
{ static void Main(string[] args) { IComponent component = new ConcreteComponent(); // 装饰者模式的使用 component = new ConcreteDecoratorA(component); // 执行操作 component.Operation(); }
}