C# 装饰器模式(Decorator Pattern)

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

// 组件接口  
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();  
    }  
}

相关推荐

  1. 【设计模式装饰模式 -- C++】

    2024-07-11 20:48:05       50 阅读
  2. C++设计模式装饰模式

    2024-07-11 20:48:05       17 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 20:48:05       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 20:48:05       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 20:48:05       58 阅读
  4. Python语言-面向对象

    2024-07-11 20:48:05       69 阅读

热门阅读

  1. 代码随想录-DAY⑦-字符串——leetcode 344 | 541 | 151

    2024-07-11 20:48:05       21 阅读
  2. FastAPI+SQLAlchemy数据库连接

    2024-07-11 20:48:05       19 阅读
  3. 关于vue监听数组

    2024-07-11 20:48:05       18 阅读
  4. SQL 自定义函数

    2024-07-11 20:48:05       22 阅读
  5. linux内核访问读写用户层文件方法

    2024-07-11 20:48:05       21 阅读
  6. RK3568平台开发系列讲解(网络篇)netfilter框架

    2024-07-11 20:48:05       19 阅读
  7. Netty服务端接收TCP链接数据

    2024-07-11 20:48:05       16 阅读
  8. 【面试题】Golang (第一篇)

    2024-07-11 20:48:05       22 阅读