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();  
    }  
}
相关推荐
专注VB编程开发20年21 小时前
阿里通义灵码插件安装失败
开发语言·ide·c#·visual studio
我爱cope21 小时前
【Agent智能体24 | 规划-创建和执行LLM计划】
人工智能·设计模式·语言模型·职场和发展
足球中国21 小时前
.net winform 仿excel控件 开源地址 https://github.com/yufb12/dataexcel_winform
.net
周杰伦fans1 天前
深入浅出AutoCAD .NET二次开发:HostApplicationServices完全解析
数据库·.net
Hillain1 天前
软件设计师设计模式
java·开发语言·经验分享·笔记·算法·设计模式·软考
影寂ldy1 天前
C# 泛型方法
java·前端·c#
caimouse1 天前
Godot 4.7 内嵌 C# 模块切换到 .NET 9.0 编译指南
c#·.net·godot
zhengfei6111 天前
第3章 Agent 类型分类与设计模式
设计模式
z落落1 天前
C# 泛型方法(原理、类型推断、多泛型参数)+泛型效率(普通类型 VS Object装箱 VS 泛型)
开发语言·c#