forked from yaocoder/DesignPattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DecoratorPattern.cpp
157 lines (110 loc) · 2.21 KB
/
DecoratorPattern.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/*
装饰着模式:动态的将责任加到对象上。想要扩展对象,装饰者提供有利于继承的另一种选择。
*/
#include <iostream>
#include <string>
using namespace std;
class Beverage
{
public:
virtual double Cost() = 0;
virtual string GetDescription()
{
return description_;
}
string description_;
};
class CondimentDecorator:public Beverage
{
public:
virtual string GetDescription() = 0;
};
class Espresso:public Beverage
{
public:
Espresso() {description_ = "Espresso";}
double Cost() { return 1.99;}
};
class DarkRoast:public Beverage
{
public:
DarkRoast() {description_ = "DarkRoast coffee";}
double Cost() { return 1.00;}
};
class HouseBlend:public Beverage
{
public:
HouseBlend() {description_ = "HouseBlend coffee";}
double Cost() { return 0.89;}
};
class Mocha :public CondimentDecorator
{
public:
Mocha(Beverage* pBeverage)
{
this->pBeverage_ = pBeverage;
}
string GetDescription()
{
return pBeverage_->GetDescription() + ", Mocha ";
}
double Cost()
{
return 0.20 + pBeverage_->Cost();
}
private:
Beverage* pBeverage_;
};
class Whip :public CondimentDecorator
{
public:
Whip(Beverage* pBeverage)
{
this->pBeverage_ = pBeverage;
}
string GetDescription()
{
return pBeverage_->GetDescription() + ", Whip ";
}
double Cost()
{
return 0.10 + pBeverage_->Cost();
}
private:
Beverage* pBeverage_;
};
class Soy :public CondimentDecorator
{
public:
Soy(Beverage* pBeverage)
{
this->pBeverage_ = pBeverage;
}
string GetDescription()
{
return pBeverage_->GetDescription() + ", Soy ";
}
double Cost()
{
return 0.30 + pBeverage_->Cost();
}
private:
Beverage* pBeverage_;
};
int main()
{
Beverage* pBeverage = new Espresso;
cout << pBeverage->GetDescription() << " $" << pBeverage->Cost() << endl;
Beverage* pBeverage2 = new DarkRoast;
pBeverage2 = new Mocha(pBeverage2);
pBeverage2 = new Whip(pBeverage2);
pBeverage2 = new Whip(pBeverage2);
cout << pBeverage2->GetDescription() << " $" << pBeverage2->Cost() << endl;
Beverage* pBeverage3 = new HouseBlend;
pBeverage3 = new Mocha(pBeverage3);
pBeverage3 = new Soy(pBeverage3);
pBeverage3 = new Whip(pBeverage3);
cout << pBeverage3->GetDescription() << " $" << pBeverage3->Cost() << endl;
system("pause");
return 0;
}