-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCoffeeDecorator.ts
108 lines (92 loc) · 2.28 KB
/
CoffeeDecorator.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
interface Coffee {
/**
* Returns the cost of the coffee.
* @returns {number} - The cost of the coffee.
*/
cost(): number;
/**
* Returns the description of the coffee.
* @returns {string} - The description of the coffee.
*/
description(): string;
}
/**
* Represents the base class for all coffee decorators.
* @abstract
* @class
*/
abstract class CoffeeDecorator implements Coffee {
/**
* Initializes the decorator with a base coffee object.
* @constructor
* @param {Coffee} coffee - The base coffee object.
*/
constructor(protected coffee: Coffee) {}
/**
* Returns the cost of the decorated coffee.
* @abstract
* @returns {number} - The cost of the decorated coffee.
*/
abstract cost(): number;
/**
* Returns the description of the decorated coffee.
* @abstract
* @returns {string} - The description of the decorated coffee.
*/
abstract description(): string;
}
/**
* Represents the base coffee without any decorations.
* @class
*/
class SimpleCoffee implements Coffee {
cost(): number {
return 1;
}
description(): string {
return 'Simple coffee';
}
}
/**
* Represents a decorator that adds milk to the coffee.
* @class
*/
class MilkDecorator extends CoffeeDecorator {
cost(): number {
return this.coffee.cost() + 0.5;
}
description(): string {
return this.coffee.description() + ', milk';
}
}
class SugarDecorator extends CoffeeDecorator {
cost(): number {
return this.coffee.cost() + 0.2;
}
description(): string {
return this.coffee.description() + ', sugar';
}
}
class WhippedCreamDecorator extends CoffeeDecorator {
cost(): number {
return this.coffee.cost() + 0.7;
}
description(): string {
return this.coffee.description() + ', whipped cream';
}
}
class CaramelDecorator extends CoffeeDecorator {
cost(): number {
return this.coffee.cost() + 0.6;
}
description(): string {
return this.coffee.description() + ', caramel';
}
}
let coffee: Coffee = new SimpleCoffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
coffee = new WhippedCreamDecorator(coffee);
coffee = new CaramelDecorator(coffee);
console.log(`Cost: $${coffee.cost()}`); // Outputs: Cost: $3.0
console.log(`Description: ${coffee.description()}`); // Outputs: Description: Simple coffee, milk, sugar, whipped cream, caramel