-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
123 lines (101 loc) · 2.29 KB
/
index.ts
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
/**
* The Decorator Pattern
*
* The Decorator Pattern attaches additional responsibilties to an object
* dynamically. Decorators provide a flexible alternative to subclassing for
* extending functionality.
*/
abstract class Beverage {
abstract cost(): number;
description = 'Unknown Beverage';
public getDescription() {
return this.description;
}
}
abstract class CondimentDecorator extends Beverage {
abstract getDescription(): string;
}
class Espresso extends Beverage {
constructor() {
super();
this.description = 'Espresso';
}
public cost() {
return 1.99;
}
}
class HouseBlend extends Beverage {
constructor() {
super();
this.description = 'House Blend Coffee';
}
public cost() {
return 0.89;
}
}
class DarkRoast extends Beverage {
constructor() {
super();
this.description = 'Dark Roast Coffee';
}
public cost() {
return 1.19;
}
}
class Mocha extends CondimentDecorator {
private beverage: Beverage;
constructor(b: Beverage) {
super();
this.beverage = b;
}
getDescription() {
return this.beverage.getDescription() + ', Mocha';
}
public cost() {
return this.beverage.cost() + 0.2;
}
}
class Whip extends CondimentDecorator {
private beverage: Beverage;
constructor(b: Beverage) {
super();
this.beverage = b;
}
getDescription() {
return this.beverage.getDescription() + ', Whip';
}
public cost() {
return this.beverage.cost() + 0.25;
}
}
class Soy extends CondimentDecorator {
private beverage: Beverage;
constructor(b: Beverage) {
super();
this.beverage = b;
}
getDescription() {
return this.beverage.getDescription() + ', Soy';
}
public cost() {
return this.beverage.cost() + 0.45;
}
}
const exampleOne = (): void => {
function printBeverage(b: Beverage) {
console.log(`${b.getDescription()} $${b.cost()}`);
}
const beverage = new Espresso();
printBeverage(beverage);
let beverage2 = new DarkRoast();
beverage2 = new Mocha(beverage2);
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);
printBeverage(beverage2);
let beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
printBeverage(beverage3);
};
export default {exampleOne};