-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.d
193 lines (152 loc) · 4.56 KB
/
decorator.d
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
module decorator;
/* Пример паттерна проектирования "Декоратор"
*
* Краткое описание ситуации:
* Требуется создать систему, которая могла бы подсчитывать стоимость кофейных
* напитков, а также опциональных дополнений, заказываемых пользователем.
* Напитки могут быть расширены впоследствии, как впрочем и дополнения.
*
* Официальное определение паттерна:
* "Паттерн Декоратор динамически наделяет объект новыми возможностями и
* является гибкой альтернативой субклассированию в области расширения
* функциональности"
*
*
* Мои пояснения:
* паттерн реализован как есть, кроме того, пришлось немного поменять модификаторы доступа,
* так как в D все немного иначе, чем в Java
*/
// общее представление напитка
public abstract class Beverage
{
// описание напитка
protected string description = "Unknown beverage";
// получить описание напитка
public string getDescription()
{
return description;
}
// стоимость напитка
public abstract double cost();
}
// опциональные дополнения к напитку
public abstract class CondimentDecorator : Beverage
{
public override abstract string getDescription();
}
// кофе "эспрессо"
public class Espresso : Beverage
{
this()
{
description = "Espresso";
}
public override double cost()
{
return 1.99;
}
}
// домашняя смесь (хз что это такое)
public class HouseBlend : Beverage
{
this()
{
description = "House Blend Coffee";
}
public override double cost()
{
return .89;
}
}
// темная обжарка
public class DarkRoast : Beverage
{
this()
{
description = "Dark Roast Coffee";
}
public override double cost()
{
return .99;
}
}
// кофе без кофеина
public class Decaf : Beverage
{
this()
{
description = "Coffee without Caffeine";
}
public override double cost()
{
return 1.05;
}
}
// шоколадное дополнение
public class Mocha : CondimentDecorator
{
private Beverage beverage;
this(Beverage beverage)
{
this.beverage = beverage;
}
public override string getDescription()
{
return beverage.getDescription() ~ ", Mocha";
}
public override double cost()
{
return beverage.cost() + 0.20;
}
}
// соевое дополнение
public class Soy : CondimentDecorator
{
private Beverage beverage;
this(Beverage beverage)
{
this.beverage = beverage;
}
public override string getDescription()
{
return beverage.getDescription() ~ ", Soy";
}
public override double cost()
{
return beverage.cost() + .15;
}
}
// дополнение в виде взбитых сливок
public class Whip : CondimentDecorator
{
private Beverage beverage;
this(Beverage beverage)
{
this.beverage = beverage;
}
public override string getDescription()
{
return beverage.getDescription() ~ ", Whip";
}
public override double cost()
{
return beverage.cost() + .10;
}
}
unittest
{
import std.stdio;
writeln("--- Decorator test ---");
Beverage beverage1 = new DarkRoast(); // темная обжарка
// собственно тут и происходит декорирование, т.е оборачивание одного объекта в другой
beverage1 = new Mocha(beverage1);
beverage1 = new Mocha(beverage1); // с двойным шоколадом
beverage1 = new Whip(beverage1); // со взбитыми сливками
writefln(beverage1.getDescription() ~ " $ %f", beverage1.cost());
Beverage beverage2 = new Decaf(); // кофе без кофеина
beverage2 = new Whip(beverage2); // со взбитыми сливками
beverage2 = new Soy(beverage2); // с соей. наверно, надо быть полным деградантом чтоб такое пить...
writefln(beverage2.getDescription() ~ " $ %f", beverage2.cost());
Beverage beverage3 = new Espresso(); // простой эспрессо
writefln(beverage3.getDescription() ~ " $ %f", beverage3.cost());
}