意图

装饰模式是一种结构型模式,允许你通过将对象放入包含行为的特殊封装对象中来为原对象绑定新的行为。

问题

假设你正在开发一个提供通知功能的库,其他程序可使用它向用户发送关于重要事件的通知。

库的最初版本基于通知器Notifier类,其中只有很少的几个成员变量,一个构造函数和一个send发送方法。该方法可以接收来自客户端的消息参数,并将该消息发送给一系列的邮箱,邮箱列表则是通过构造函数传递给通知器的。作为客户端的第三方程序仅会创建和配置通知器对象一次,然后在有重要事件发生时对其进行调用。

程序可以使用通知器类向预定义的邮箱发送重要事件通知

此后某个时刻,你会发现库的用户希望使用除邮件通知之外的功能。许多用户会希望接收关于紧急事件的手机短信,还有些用户希望在微信上接收消息,而公司用户则希望在 QQ 上接收消息。

每种通知类型都将作为通知器的一个子类得以实现

这有什么难的呢?首先扩展通知器类,然后在新的子类中加入额外的通知方法。现在客户端要对所需通知形式的对应类进行初始化,然后使用该类发送后续所有的通知消息。

但是很快有人会问:​“为什么不同时使用多种通知形式呢?如果房子着火了,你大概会想在所有渠道中都收到相同的消息吧。”

你可以尝试创建一个特殊子类来将多种通知方法组合在一起以解决该问题。但这种方式会使得代码量迅速膨胀,不仅仅是程序库代码,客户端代码也会如此。

子类组合数量爆炸

你必须找到其他方法来规划通知类的结构,否则它们的数量会在不经意之间打破吉尼斯纪录。

解决方案

当你需要更改一个对象的行为时,第一个跳入脑海的想法就是扩展它所属的类。但是,你不能忽视继承可能引发的几个严重问题。

  • 继承是静态的。你无法在运行时更改已有对象的行为,只能使用由不同子类创建的对象来替代当前的整个对象。
  • 子类只能有一个父类。大部分编程语言不允许一个类同时继承多个类的行为。

其中一种方法是用聚合或组合,而不是继承。两者的工作方式几乎一模一样:一个对象包含指向另一个对象的引用,并将部分工作委派给引用对象;继承中的对象则继承了父类的行为,它们自己能够完成这些工作。

聚合:对象 A 包含对象 B;B 可以独立于 A 存在。
组合:对象 A 由对象 B 构成;A 负责管理 B 的生命周期。B 无法独立于 A 存在。

你可以使用这个新方法来轻松替换各种连接的“小帮手”对象,从而能在运行时改变容器的行为。一个对象可以使用多个类的行为,包含多个指向其他对象的引用,并将各种工作委派给引用对象。

聚合(或组合)组合是许多设计模式背后的关键原则(包括装饰在内)。

继承与聚合的对比

封装器是装饰模式的别称,这个称谓明确地表达了该模式的主要思想。​“封装器”是一个能与其他“目标”对象连接的对象。封装器包含与目标对象相同的一系列方法,它会将所有接收到的请求委派给目标对象。但是,封装器可以在将请求委派给目标前后对其进行处理,所以可能会改变最终结果。

那么什么时候一个简单的封装器可以被称为是真正的装饰呢?正如之前提到的,封装器实现了与其封装对象相同的接口。因此从客户端的角度来看,这些对象是完全一样的。封装器中的引用成员变量可以是遵循相同接口的任意对象。这使得你可以将一个对象放入多个封装器中,并在对象中添加所有这些封装器的组合行为。

比如在消息通知示例中,我们可以将简单邮件通知行为放在基类 通知器中,但将所有其他通知方法放入装饰中。

将各种通知方法放入装饰

客户端代码必须将基础通知器放入一系列自己所需的装饰中。因此最后的对象将形成一个栈结构。

程序可以配置由通知装饰构成的复杂栈

实际与客户端进行交互的对象将是最后一个进入栈中的装饰对象。由于所有的装饰都实现了与通知基类相同的接口,客户端的其他代码并不在意自己到底是与“纯粹”的通知器对象,还是与装饰后的通知器对象进行交互。

我们可以使用相同方法来完成其他行为(例如设置消息格式或者创建接收人列表)。只要所有装饰都遵循相同的接口,客户端就可以使用任意自定义的装饰来装饰对象。

结构

  1. 部件(Component)声明封装器和被封装对象的公用接口。
  2. 具体部件(Concrete Component)类是被封装对象所属的类。它定义了基础行为,但装饰类可以改变这些行为。
  3. 基础装饰(Base Decorator)类拥有一个指向被封装对象的引用成员变量。该变量的类型应当被声明为通用部件接口,这样它就可以引用具体的部件和装饰。装饰基类会将所有操作委派给被封装的对象。
  4. 具体装饰类(Concrete Decorators)定义了可动态添加到部件的额外行为。具体装饰类会重写装饰基类的方法,并在调用父类方法之前或之后进行额外的行为。
  5. 客户端(Client)可以使用多层装饰来封装部件,只要它能使用通用接口与所有对象互动即可。

实现方式

  1. 确保业务逻辑可用一个基本组件及多个额外可选层次表示。
  2. 找出基本组件和可选层次的通用方法。创建一个组件接口并在其中声明这些方法。
  3. 创建一个具体组件类,并定义其基础行为。
  4. 创建装饰基类,使用一个成员变量存储指向被封装对象的引用。该成员变量必须被声明为组件接口类型,从而能在运行时连接具体组件和装饰。装饰基类必须将所有工作委派给被封装的对象。
  5. 确保所有类实现组件接口。
  6. 将装饰基类扩展为具体装饰。具体装饰必须在调用父类方法(总是委派给被封装对象)之前或之后执行自身的行为。
  7. 客户端代码负责创建装饰并将其组合成客户端所需的形式。

代码演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;

namespace RefactoringGuru.DesignPatterns.Composite.Conceptual
{
// The base Component interface defines operations that can be altered by
// decorators.
public abstract class Component
{
public abstract string Operation();
}

// Concrete Components provide default implementations of the operations.
// There might be several variations of these classes.
class ConcreteComponent : Component
{
public override string Operation()
{
return "ConcreteComponent";
}
}

// The base Decorator class follows the same interface as the other
// components. The primary purpose of this class is to define the wrapping
// interface for all concrete decorators. The default implementation of the
// wrapping code might include a field for storing a wrapped component and
// the means to initialize it.
abstract class Decorator : Component
{
protected Component _component;

public Decorator(Component component)
{
this._component = component;
}

public void SetComponent(Component component)
{
this._component = component;
}

// The Decorator delegates all work to the wrapped component.
public override string Operation()
{
if (this._component != null)
{
return this._component.Operation();
}
else
{
return string.Empty;
}
}
}

// Concrete Decorators call the wrapped object and alter its result in some
// way.
class ConcreteDecoratorA : Decorator
{
public ConcreteDecoratorA(Component comp) : base(comp)
{
}

// Decorators may call parent implementation of the operation, instead
// of calling the wrapped object directly. This approach simplifies
// extension of decorator classes.
public override string Operation()
{
return $"ConcreteDecoratorA({base.Operation()})";
}
}

// Decorators can execute their behavior either before or after the call to
// a wrapped object.
class ConcreteDecoratorB : Decorator
{
public ConcreteDecoratorB(Component comp) : base(comp)
{
}

public override string Operation()
{
return $"ConcreteDecoratorB({base.Operation()})";
}
}

public class Client
{
// The client code works with all objects using the Component interface.
// This way it can stay independent of the concrete classes of
// components it works with.
public void ClientCode(Component component)
{
Console.WriteLine("RESULT: " + component.Operation());
}
}

class Program
{
static void Main(string[] args)
{
Client client = new Client();

var simple = new ConcreteComponent();
Console.WriteLine("Client: I get a simple component:");
client.ClientCode(simple);
Console.WriteLine();

// ...as well as decorated ones.
//
// Note how decorators can wrap not only simple components but the
// other decorators as well.
ConcreteDecoratorA decorator1 = new ConcreteDecoratorA(simple);
ConcreteDecoratorB decorator2 = new ConcreteDecoratorB(decorator1);
Console.WriteLine("Client: Now I've got a decorated component:");
client.ClientCode(decorator2);
}
}
}

执行结果:

1
2
3
4
5
Client: I get a simple component:
RESULT: ConcreteComponent

Client: Now I've got a decorated component:
RESULT: ConcreteDecoratorB(ConcreteDecoratorA(ConcreteComponent))

参考原文:装饰设计模式