-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.cpp
74 lines (60 loc) · 1.73 KB
/
main.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
/*
* @FileName : decorator/main.cpp
* @CreateAt : 2022/4/14
* @Author : Inno Fang
* @Email : [email protected]
* @Description: Simple implementation of decorator pattern
*/
#include <iostream>
#include <string>
class Component {
public:
virtual ~Component() = default;
virtual std::string operation() = 0;
};
class ConcreteComponent : public Component {
public:
std::string operation() override {
return "ConcreteComponent";
}
};
class Decorator : public Component {
public:
explicit Decorator(Component *component)
: _component(component) {}
std::string operation() override {
return _component->operation();
}
protected:
Component *_component;
};
class ConcreteDecoratorA : public Decorator {
public:
explicit ConcreteDecoratorA(Component *component)
: Decorator(component) {}
std::string operation() override {
return "ConcreteDecoratorA(" + Decorator::operation() + ")";
}
};
class ConcreteDecoratorB : public Decorator {
public:
explicit ConcreteDecoratorB(Component *component)
: Decorator(component) {}
std::string operation() override {
return "ConcreteDecoratorB(" + Decorator::operation() + ")";
}
};
int main() {
Component *simple = new ConcreteComponent;
std::cout << "Simple component:" << std::endl;
std::cout << simple->operation() << std::endl;
std::cout << std::endl;
Decorator *decoratorA = new ConcreteDecoratorA(simple);
Decorator *decoratorB = new ConcreteDecoratorB(decoratorA);
std::cout << "Decorator component:" << std::endl;
std::cout << decoratorB->operation() << std::endl;
delete decoratorB;
delete decoratorA;
delete simple;
return 0;
}