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();  
    }  
}
相关推荐
CSharp精选营34 分钟前
我把 Ant Design Blazor 翻了一遍:Blazor 中后台组件库到底能不能用
.net·blazor·ant design blazor·中后台系统·mudblazor
IT规划师42 分钟前
Redis 数据类型全解 - ZSet:两个编码,七种玩法(五)
redis·.net
是2的10次方啊1 小时前
设计模式与生活⑪:地铁里被打扰,别总靠自己硬扛
设计模式
吃一碗粉只付一碗钱11 小时前
16-SqlSugar多库ConfigId与按实体选连接
sqlserver·c#
rockey62713 小时前
AScript之字符串模板
c#·.net·script·expression·动态脚本
will_net13 小时前
Redis集群部署+Redis 链接地址放入Aollo +c#项目接入Redis
redis·c#·bootstrap
高晶14 小时前
SPMI 控制器 RTL 设计与验证新手入门
设计模式·程序员·架构
BuHuaX20 小时前
Lua 与 ToLua:运行机制及热更新原理
开发语言·unity·junit·c#·lua
asdzx6721 小时前
C# 操作 PDF 元数据:从属性写入到字段提取的完整流程
前端·pdf·c#