设计模式系列之装饰器模式(Decorator Pattern)

本文简单讲述装饰模式

功能

**装饰模式(Decorator Pattern)**可以动态的给一个对象添加额外的功能。

也就是可以在保持原始功能的情况下对原始功能增加额外的修饰能力的模式,例如人可以使用衣服来装饰自己的外表。

UML结构图

实例

人物衣着装饰

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
#include "pch.h"
#include <iostream>
using namespace std;

//原本类
class Person {
public :
Person() {};
Person(char* name){
this->name = name;
}

virtual void show() {
cout << name<< endl;
}

private:
char* name;
};

//服装类
class Clothes : public Person {
protected:
Person * component;

public:
void decorate(Person * component) {
this->component = component;
}

virtual void show() {
if (component != NULL) {
component->show();
}
}
};

//具体服装类
class Tshirts : public Clothes {
public:
Tshirts(int number) {
this->number = number;
}

virtual void show() {
cout << number << "号体恤 ";
Clothes::show();
}

private:
int number;
};

class Jeans : public Clothes {
public:
virtual void show() {
cout << "牛仔裤 ";
Clothes::show();
}

private:
int number;
};

int main()
{
char name[] = "爱和圣殿";
Person person(name);
Tshirts tshirts(11);
Jeans jeans;

tshirts.decorate(&person);
jeans.decorate(&tshirts);

jeans.show();
}

在这个实例中看到牛仔裤调用show一般很容易让人晕,其实这里的牛仔裤在工厂函数输出后是一个person对象,经过修饰后的一个人!,这里很容易被误导

END

2018-10-11 完成

2018-10-11 立项