设计模式-装饰器模式

以下是一个简单的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(),然后输出额外的信息,演示了装饰器如何增加功能的过程。

相关推荐
geovindu1 天前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
宝桥南山1 天前
GitHub Models - 尝试一下使用GitHub Models
microsoft·ai·微软·c#·github·.netcore
hixiong1231 天前
C# OpenvinoSharp部署INSID3
开发语言·人工智能·ai·c#·openvinosharp
嵌入式学习_force1 天前
02_state
设计模式·蓝牙
星辰徐哥1 天前
Unity C#入门:变量的定义与访问权限(public/private)
unity·c#·lucene
leoufung1 天前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
hacker7071 天前
Visual Studio安装教程(C#开发版)
ide·c#·visual studio
SKY -dada1 天前
Understand 使用教程
开发语言·c#·流程图·软件构建·敏捷流程·代码复审·源代码管理
qcx231 天前
Warp源码深度解析(七):Token预算策略——双轨计费、上下文溢出与摘要压缩
人工智能·设计模式·rust·wrap
William_cl1 天前
【C#/.NET 进阶】ASP.NET 架构与最佳实践:DI 依赖注入(IoC 核心)从入门到避坑
c#·asp.net·.net