设计模式-装饰器模式

以下是一个简单的C#装饰器模式示例,它展示了如何实现一个装饰器来增加一个对象的功能。

cs 复制代码
// 组件基类
public abstract class Component
{
    public abstract void Operation();
}
 
// 具体组件
public class ConcreteComponent : Component
{
    public override void Operation()
    {
        Console.WriteLine("具体操作。");
    }
}
 
// 装饰器抽象类
public abstract class Decorator : Component
{
    protected Component component;
 
    public Decorator(Component component)
    {
        this.component = component;
    }
 
    public override void Operation()
    {
        if (component != null)
        {
            component.Operation();
        }
    }
}
 
// 具体装饰器
public class ConcreteDecoratorA : Decorator
{
    public ConcreteDecoratorA(Component component) : base(component) { }
 
    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("具体装饰器A的操作。");
    }
}
 
// 客户端代码
class Program
{
    static void Main(string[] args)
    {
        // 创建一个具体组件对象
        Component component = new ConcreteComponent();
 
        // 创建一个具体装饰器对象,并将组件作为参数传入
        Decorator decorator = new ConcreteDecoratorA(component);
 
        // 调用装饰器的操作方法,它将首先调用组件的操作方法,然后添加额外的操作
        decorator.Operation();
    }
}

这个例子中,ConcreteComponent 类表示一个基本的对象,而 ConcreteDecoratorA 类是装饰器,它扩展了 ConcreteComponent 的功能。在 Main 方法中,我们首先创建了一个 ConcreteComponent 对象,然后用这个对象作为参数创建了一个 ConcreteDecoratorA 对象。当我们调用 decorator.Operation() 时,它将首先调用 component.Operation(),然后输出额外的信息,演示了装饰器如何增加功能的过程。

相关推荐
似水明俊德1 天前
02-C#.Net-反射-面试题
开发语言·面试·职场和发展·c#·.net
阿蒙Amon1 天前
C#常用类库-详解SerialPort
开发语言·c#
似水明俊德1 天前
02-C#.Net-反射-学习笔记
开发语言·笔记·学习·c#·.net
.NET修仙日记2 天前
Acme.ReturnOh:让.NET API返回值处理更优雅,统一响应格式一步到位
c#·.net·webapi
阿蒙Amon2 天前
C#常用类库-详解YamlDotNet
开发语言·c#
Sunsets_Red2 天前
乘法逆元的 exgcd 求法
c++·学习·数学·算法·c#·密码学·信息学竞赛
唐青枫2 天前
深入理解 C#.NET TaskScheduler:为什么大量使用 Work-Stealing
c#·.net
szm02252 天前
设计模式-
设计模式
砍光二叉树2 天前
【设计模式】创建型-抽象工厂模式
设计模式·抽象工厂模式
人工智能AI技术2 天前
Claude 3.7 企业版私有化部署技术验证:与 .NET 实战方案
人工智能·c#