-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decorator.cpp
95 lines (84 loc) · 1.98 KB
/
Decorator.cpp
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
#include <iostream>
#include <string>
using namespace std;
class Component{
public:
virtual void operation(){};
Component(){
cout << "Component 构造" << endl;
}
~Component(){
cout << "Component 析构" << endl;
}
};
class ConcreteComponent:public Component{
public:
ConcreteComponent(string name){
cout << "ConcreteComponent 构造" << endl;
this->name = name;
}
~ConcreteComponent(){
cout << "ConcreteComponent 析构" << endl;
}
void operation(){
cout << name << endl;
}
private:
string name;
};
class Decorate : public Component{
public:
void setComponent(Component* component){
this->component = component;
}
virtual void operation(){
if(component != nullptr){
component->operation();
}
}
Decorate(){
cout << "Decorate 构造" << endl;
}
~Decorate(){
cout << "Decorate 析构" << endl;
}
private:
Component* component = nullptr;
};
class DecorateA : public Decorate{
public:
void operation(){
Decorate::operation();
cout << "DecorateA Operation" << endl;
}
~DecorateA(){
cout << "DecorateA 析构" << endl;
}
DecorateA(){
cout << "DecorateA 构造" << endl;
}
};
class DecorateB : public Decorate{
public:
void operation(){
Decorate::operation();
cout << "DecorateB Operation" << endl;
}
~DecorateB(){
cout << "DecorateB 析构" << endl;
}
DecorateB(){
cout << "DecorateB 构造" << endl;
}
};
int main(){
ConcreteComponent* person = new ConcreteComponent("student1");
DecorateA* chinese = new DecorateA();
DecorateB* english = new DecorateB();
chinese->setComponent(person);
english->setComponent(chinese);
english->operation();
delete english;
delete chinese;
delete person;
}