装饰器模式

装饰器模式是一种结构型设计模式,它允许在不改变原有对象结构的情况下,动态地添加额外的功能或责任到对象上。这种模式通过创建包装类(装饰器类)来包裹原始类实例,并提供额外的功能。

以下是一个简单的装饰器模式的示例代码:

using System;

// 抽象组件接口
interface IComponent
{
    void Operation();
}

// 具体组件类
class ConcreteComponent : IComponent
{
    public void Operation()
    {
        Console.WriteLine("This is the core operation of the component.");
    }
}

// 抽象装饰器类
abstract class Decorator : IComponent
{
    protected IComponent component;

    public Decorator(IComponent component)
    {
        this.component = component;
    }

    public virtual void Operation()
    {
        if (component != null)
        {
            component.Operation();
        }
    }
}

// 具体装饰器类A
class ConcreteDecoratorA : Decorator
{
    public ConcreteDecoratorA(IComponent component) : base(component) { }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("Added behavior from ConcreteDecoratorA.");
    }
}

// 具体装饰器类B
class ConcreteDecoratorB : Decorator
{
    public ConcreteDecoratorB(IComponent component) : base(component) { }

    public override void Operation()
    {
        base.Operation();
        Console.WriteLine("Added behavior from ConcreteDecoratorB.");
    }
}

class Program
{
    static void Main()
    {
        // 创建一个具体组件实例
        IComponent component = new ConcreteComponent();

        // 用具体装饰器A装饰组件
        Decorator decoratorA = new ConcreteDecoratorA(component);
        decoratorA.Operation();

        Console.WriteLine();

        // 用具体装饰器B装饰组件
        Decorator decoratorB = new ConcreteDecoratorB(component);
        decoratorB.Operation();
    }
}

在上面的代码中,我们定义了一个抽象组件接口 IComponent,具体组件类 ConcreteComponent 实现了该接口。然后定义了一个抽象装饰器类 Decorator,它包含一个指向组件的引用,并且可以在调用组件操作时添加额外的行为。具体装饰器类 ConcreteDecoratorA 和 ConcreteDecoratorB 分别继承自装饰器类,并实现了特定的增强功能。

在 Main() 方法中,我们首先创建一个具体组件实例,然后用具体装饰器类A和B分别装饰这个组件实例,从而实现对组件功能的动态扩展。

这个例子演示了如何使用装饰器模式来动态地为对象添加新的功能,同时保持原有对象结构不变。

posted @ 2024-09-09 15:01  电器小君子  阅读(29)  评论(0)    收藏  举报