-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.ts
105 lines (85 loc) · 2.61 KB
/
decorator.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
/**
* **Decorator**
*
* > "Attach additional responsibilities to an object dynamically.
* Decorators provide a flexible alternative to subclassing for
* extending functionality."
*
* While _decorators_ are a feature of many languages, this is also
* a general pattern we can use in any object-oriented language.
*
* The pattern is also called a "wrapper", which makes sense, as
* what we do here is encapsulating one class within another to
* gain extra features.
*
* In the example we'll use look at getting ice cream with,
* or without, extra toppings.
*
* @see https://refactoring.guru/design-patterns/decorator
* @see https://en.wikipedia.org/wiki/Decorator_pattern
* @see Page 175 in `Design Patterns - Elements of Reusable Object-Oriented Software`
*/
function decoratorDemo() {
// The ice cream interface
interface IceCream {
getDescription(): string;
cost(): number;
}
// The basic ice cream variants
class VanillaIceCream implements IceCream {
getDescription() {
return 'Vanilla Ice Cream';
}
cost() {
return 2.5;
}
}
class ChocolateIceCream implements IceCream {
getDescription() {
return 'Chocolate Ice Cream';
}
cost() {
return 3.0;
}
}
// An abstract class that we will override in the decorators
abstract class IceCreamDecorator implements IceCream {
constructor(private iceCream: IceCream) {
//
}
getDescription() {
return this.iceCream.getDescription();
}
cost() {
return this.iceCream.cost();
}
}
// The decorators override (`super()`) the functionality from the `IceCreamDecorator` and add the extras
class SprinklesDecorator extends IceCreamDecorator {
getDescription() {
return `${super.getDescription()} with sprinkles ✨`;
}
cost() {
return super.cost() + 0.5;
}
}
class CherryDecorator extends IceCreamDecorator {
getDescription() {
return `${super.getDescription()} with a cherry on top 🍒`;
}
cost() {
return super.cost() + 1.0;
}
}
// Using it "vanilla" (bad pun intended)
let iceCream: IceCream = new VanillaIceCream();
console.log(`${iceCream.getDescription()} - $${iceCream.cost()}`);
iceCream = new ChocolateIceCream();
console.log(`${iceCream.getDescription()} - $${iceCream.cost()}`);
// Using it wrapped in a decorator
iceCream = new SprinklesDecorator(new VanillaIceCream());
console.log(`${iceCream.getDescription()} - $${iceCream.cost()}`);
iceCream = new CherryDecorator(new ChocolateIceCream());
console.log(`${iceCream.getDescription()} - $${iceCream.cost()}`);
}
decoratorDemo();