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();  
    }  
}
相关推荐
DanmF--5 分钟前
C#面向对象实践项目--贪吃蛇
开发语言·游戏·c#·游戏程序
YGGP1 小时前
【结构型模式】代理模式
设计模式
凌康ACG2 小时前
易语言使用OCR
c++·yolo·c#·ocr·易语言
InCerry2 小时前
.NET 9中的异常处理性能提升分析:为什么过去慢,未来快
c#·.net·高性能
webmote333 小时前
DeepSeek私域数据训练之封装Anything LLM的API 【net 9】
.net·api·deepseek
@蓝莓果粒茶4 小时前
LeetCode第244题_最短单词距离II
c++·笔记·学习·算法·leetcode·职场和发展·c#
端阳月七5 小时前
C#面试问题61-80
开发语言·c#
蓝点lilac5 小时前
C# Task 取消执行的简单封装
c#·.net·多线程
庄小焱6 小时前
设计模式——中介者设计模式(行为型)
设计模式
端阳月七6 小时前
C#面试问题81-100
开发语言·面试·c#