-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathObject-装饰者(☕️).js
94 lines (82 loc) · 2.38 KB
/
Object-装饰者(☕️).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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*----------------------------------------------------------------------------------
* about:装饰模式是一种结构型设计模式, 允许你通过将对象放入包含行为的特殊封装对象中来为原对象绑定新的行为。
* 加工函数的封装后,可以明显地看到链式加工。简洁,扩展性强
* author:马兆铿(810768333@qq.com)
* date:2019-12-25
* ----------------------------------------------------------------------------------*/
class Beverage {
constructor() {
this.price = 0
}
getDescription() {
return this.constructor.name + ' Coffee: '
}
cost() {
return `$${this.price.toFixed(2)}`
}
}
/* ----------------------------------------- 子类 ----------------------------------------- */
class HouseBlend extends Beverage { // mocha,mocha,whip
constructor() {
super() // 继承(方法)
let beverage = new Beverage() // 继承(属性)
beverage = new Mocha(beverage) // 装饰
beverage = new Mocha(beverage)
beverage = new Whip(beverage)
Object.assign(this, beverage) // 合并
}
}
class DarkRoast extends Beverage { // soy,mocha,whip
constructor() {
super()
let beverage = new Beverage()
beverage = new Soy(beverage)
beverage = new Mocha(beverage)
beverage = new Whip(beverage)
Object.assign(this, beverage)
}
}
/* ----------------------------------------- 装饰者 ----------------------------------------- */
class CondimentDecorator {
getDescription() {
return this.constructor.name
}
cost() {
return this.price
}
}
/* ----------------------------------------- 材料 ----------------------------------------- */
class Mocha extends CondimentDecorator {
constructor(beverage) {
super()
beverage.price += 0.2
return beverage
}
}
class Milk extends CondimentDecorator {
constructor(beverage) {
super()
beverage.price += 0.1
return beverage
}
}
class Soy extends CondimentDecorator {
constructor(beverage) {
super()
beverage.price += 0.4
return beverage
}
}
class Whip extends CondimentDecorator {
constructor(beverage) {
super()
beverage.price += 0.3
return beverage
}
}
// 模拟购买
const houseBlend = new HouseBlend()
const darkRoast = new DarkRoast()
console.log('<JS Coffee Shop>')
console.log(houseBlend.getDescription(), houseBlend.cost())
console.log(darkRoast.getDescription(), darkRoast.cost())