C# 装饰器模式(Decorator Pattern)

装饰器模式动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。

cs 复制代码
// 组件接口  
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();  
    }  
}
相关推荐
林川~016 小时前
Unity 万能物理检测工具:射线检测 / 范围检测 / 层级过滤 / 编辑器可视化(可直接拿去用)
游戏·unity·c#·射线检测·通用工具
xiaofeiyang1507 小时前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
He BianGu10 小时前
【WPF-VisionMaster】机器视觉通用平台V5.0版本发行说明
opencv·c#·wpf·halcon·机器视觉·visionmaster
tang_042710 小时前
【Hi.Ltd 专题】第9期:Interop 配置互操作(JSON/INI/XML/YAML/注册表/扫码)
经验分享·c#·hi.ltd系列
tang_042716 小时前
【Hi.Ltd 专题】第7期:Threading 采集线程、锁与 LRU 缓存
经验分享·c#·hi.ltd系列
A_nanda16 小时前
C# 界面卡顿:从定位到根治
c#
2501_9307077817 小时前
使用C#代码为新创建的 Word 文档创建目录
c#·word
czhc114007566318 小时前
同一个数,两把尺子:六组“看着一样、其实不一样“
c#
花北城19 小时前
【C#底层库】access_token授权鉴权验证
c#·鉴权·token·授权
rick97720 小时前
C# 动态代理与 DispatchProxy:从原理到实战的完整指南
c#