设计模式笔记:装饰器模式

是一种结构型设计模式,允许用户在不改变现有对象结构的情况下向现有对象添加新的功能。

示例

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
#include <iostream>
using namespace std;

class Car {
public:
virtual void ShowMessage()
{
cout << "Base Car" << endl;
}
};

class Decorator : public Car{
public:
Decorator() = default;
Decorator(Car *car) : car_(car) {}
void ShowMessage()
{
if (car_) {
car_->ShowMessage();
cout << "Add function!" << endl;
}
}

private:
Car* car_ = nullptr;
};

class DecoratorA : public Decorator{
public:
DecoratorA(Car *car) : car_(car) {}
void ShowMessage()
{
if (car_) {
car_->ShowMessage();
cout << "Add auto {ai} function!" << endl;
}
}

private:
Car* car_ = nullptr;
};

class DecoratorB : public Decorator{
public:
DecoratorB(Car *car) : car_(car) {}
void ShowMessage()
{
if (car_) {
car_->ShowMessage();
cout << "Add auto {run} function!" << endl;
}
}

private:
Car* car_ = nullptr;
};

int main()
{
Car* car = new Car();
car->ShowMessage();
cout << "---------" << endl;
Car* addA = new DecoratorA(car);
addA->ShowMessage();
cout << "=========" << endl;
Car* addB = new DecoratorB(addA);
addB->ShowMessage();
return 0;
}
1
2
3
4
5
6
7
8
Base Car
---------
Base Car
Add auto {ai} function!
=========
Base Car
Add auto {ai} function!
Add auto {run} function!

总结:核心在于装饰器基类继承原始基类,使得能够动态增加功能