-
Notifications
You must be signed in to change notification settings - Fork 0
/
Decorator.cpp
109 lines (90 loc) · 1.66 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <string>
using namespace std;
//Beverage抽象基类
class Beverage
{
public:
Beverage()
{
_desc = "unknown beverage";
}
//虚析构函数,当类中有虚函数时,则必须显示声明虚析构函数
//纯虚析构函数则()后=0,
virtual ~Beverage() {};
virtual string get_desc() const
{
return _desc;
}
virtual int cost() const = 0;
protected:
string _desc;
};
//Condiment装饰者类
class CondimentDecorator : public Beverage
{
public:
virtual ~CondimentDecorator() {};
virtual string get_desc() const = 0;
};
//Espresso class
class Espresso : public Beverage
{
public:
Espresso()
{
_desc = "Espresso";
}
int cost() const
{
return 2;
}
};
//House Blend class
class HouseBlend : public Beverage
{
public:
HouseBlend()
{
_desc = "House Blend Coffee";
}
int cost() const
{
return 1;
}
};
//Mocha class
class Mocha : public CondimentDecorator
{
public:
Mocha(Beverage *beverage)
{
_beverage = beverage;
}
~Mocha()
{
delete _beverage;
}
string get_desc() const
{
return _beverage->get_desc() + ", Mocha";
}
int cost() const
{
return 1 + _beverage->cost();
}
private:
const Beverage *_beverage;
};
int main(int argc, char *argv[])
{
Beverage *beverage = new Espresso();
cout << beverage->get_desc() << ": $" << beverage->cost() << endl;
beverage = new Mocha(beverage);
cout << beverage->get_desc() << ": $" << beverage->cost() << endl;
Beverage *beverage2 = new HouseBlend();
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
cout << beverage2->get_desc() << ": $" << beverage2->cost() << endl;
return 0;
}