-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDecorator.js
78 lines (64 loc) · 1.69 KB
/
Decorator.js
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
// Decorator is a structural pattern.
// Декоратор - структурный шаблон проектирования.
class Chocolate {
constructor() {
this.price = 10;
this.info = 'Chocolate';
}
getPrice() {
return this.price;
}
getInfo() {
return this.info;
}
}
class MilkChocolate extends Chocolate {
constructor() {
super();
this.price = 12;
this.info = 'Milk chocolate';
}
}
class DarkChocolate extends Chocolate {
constructor() {
super();
this.price = 14;
this.info = 'Dark chocolate';
}
}
// Decorator (Декоратор)
class Nuts {
constructor(chocolate) {
this.info = chocolate;
}
getPrice() {
return this.info.getPrice() + 2;
}
getInfo() {
return `${this.info.getInfo()} with nuts`;
}
}
// Decorator (Декоратор)
class Raisins {
constructor(chocolate) {
this.info = chocolate;
}
getPrice() {
return this.info.getPrice() + 1;
}
getInfo() {
return `${this.info.getInfo()} with raisins`;
}
}
// Instances (Экземпляры)
let myMilkChocolate1 = new MilkChocolate();
let myMilkChocolate2 = new MilkChocolate();
let myDarkChocolate1 = new DarkChocolate();
// Decorate them (Декорируем их)
myMilkChocolate1 = new Nuts(myMilkChocolate1);
myMilkChocolate1 = new Raisins(myMilkChocolate1);
myMilkChocolate2 = new Nuts(myMilkChocolate2);
myDarkChocolate1 = new Nuts(myDarkChocolate1);
console.log(`Chocolate: ${myMilkChocolate1.getInfo()}, Price: ${myMilkChocolate1.getPrice()}`);
console.log(`Chocolate: ${myMilkChocolate2.getInfo()}, Price: ${myMilkChocolate2.getPrice()}`);
console.log(`Chocolate: ${myDarkChocolate1.getInfo()}, Price: ${myDarkChocolate1.getPrice()}`);