Skip to content

装饰器模式

在不改变对象结构的前提下,动态地为对象添加功能。

它不是直接改类,也不靠继承,而是用“包装”的方式扩展功能

适合的场景

  • 类已经写好了,不能随便改。

  • 继承不够灵活,功能组合太麻烦。

  • 想动态添加或移除功能,而不是写死。

  • 想要功能叠加,又不想影响原始逻辑。

超级适合用来“功能扩展”但又不能动原本类的场景

基本结构

  1. Component(组件接口):定义功能接口

  2. ConcreteComponent(具体组件):实现基础功能

  3. Decorator(抽象装饰器):持有一个组件引用,实现接口

  4. ConcreteDecorator(具体装饰器):在原有功能基础上添加新功能!

示例

csharp
// 组件接口
public interface INotifier
{
    void Send(string message);
}

// 具体实现
public class EmailNotifier : INotifier
{
    public void Send(string message)
    {
        Console.WriteLine($"发送邮件: {message}");
    }
}

// 抽象装饰器
public abstract class NotifierDecorator : INotifier
{
    protected INotifier notifier;

    public NotifierDecorator(INotifier notifier)
    {
        this.notifier = notifier;
    }

    public virtual void Send(string message)
    {
        notifier.Send(message);
    }
}

// 具体装饰器:短信功能
public class SMSNotifier : NotifierDecorator
{
    public SMSNotifier(INotifier notifier) : base(notifier) {}

    public override void Send(string message)
    {
        base.Send(message);
        Console.WriteLine($"发送短信: {message}");
    }
}

// 具体装饰器:微信功能
public class WeChatNotifier : NotifierDecorator
{
    public WeChatNotifier(INotifier notifier) : base(notifier) {}

    public override void Send(string message)
    {
        base.Send(message);
        Console.WriteLine($"发送微信: {message}");
    }
}

使用

// 基础邮件通知
INotifier notifier = new EmailNotifier();

// 动态添加短信通知
notifier = new SMSNotifier(notifier);

// 再添加微信通知
notifier = new WeChatNotifier(notifier);

// 或者:INotifier notifier = new WeChatNotifier(new SMSNotifier(new EmailNotifier()));

// 调用时会依次执行:邮件 → 短信 → 微信
notifier.Send("Ciallo~(∠・▽< )⌒☆");

/* 
输出:
发送邮件: Ciallo~(∠・▽< )⌒☆
发送短信: Ciallo~(∠・▽< )⌒☆
发送微信: Ciallo~(∠・▽< )⌒☆
*/

GDScript示例:

gdscript
# 基础接口
class Notifier:
    func send(message: String) -> void:
        pass

# 基本实现
class EmailNotifier extends Notifier:
    func send(message: String) -> void:
        print("发送邮件: %s" % message)

# 装饰器基类
class NotifierDecorator extends Notifier:

    var notifier: Notifier

    func _init(notifier: Notifier) -> void:
        self.notifier = notifier

    func send(message: String) -> void:
        notifier.send(message)

# 短信装饰器
class SMSNotifier extends NotifierDecorator:
    func send(message: String) -> void:
        super(message)
        print("发送短信: %s" % message)

# 微信装饰器
class WeChatNotifier extends NotifierDecorator:
    func send(message: String) -> void:
        super(message)
        print("发送微信: %s" % message)

# 使用
func _ready():
    var notifier : Notifier = EmailNotifier.new()
    notifier = SMSNotifier.new(notifier)
    notifier = WeChatNotifier.new(notifier)
    # 或者 var notifier := WeChatNotifier.new(SMSNotifier.new(EmailNotifier.new()))
    notifier.send("٩(๑•̀ω•́๑)۶:Ciallo~(∠・▽< )⌒☆ ")