-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorator.js
85 lines (75 loc) · 1.5 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
79
80
81
82
83
84
85
function Man() {
console.log('我是战士')
}
Man.prototype = {
sayName: function() {
console.log('我是一等战士')
},
attack: function() {
console.log('拳击')
},
defend: function() {
console.log('防御')
}
}
var man = new Man()
// 装饰器类
function Decorator(man) {
this.man = man
}
Decorator.prototype = {
sayName: function() {
this.man.sayName()
},
attack: function() {
this.man.attack()
},
defend: function() {
this.man.defend()
}
}
function ManGun(man) {
Decorator.call(this, man)
}
ManGun.prototype = {
sayName: function() {
console.log('我是有枪的战士')
},
attack: function() {
console.log('开枪攻击')
},
defend: function() {
console.log('防御加🔟')
}
}
function ManKnife(man) {
Decorator.call(this, man)
}
ManKnife.prototype = {
sayName: function() {
console.log('我还是有刀的战士')
},
attack: function() {
console.log('开枪和用刀')
},
defend: function() {
console.log('防御加1')
}
}
var manGun = new ManGun(man)
man.sayName()
man.attack()
man.defend()
console.log('---------')
manGun.sayName()
manGun.attack()
manGun.defend()
var manKnife = new ManKnife(man)
console.log('---------')
manKnife.sayName()
// manKnife.attack()
manKnife.defend()
// 原生js继承问题
// 1、子类一定要实现父类的方法,导致代码臃肿
// 2、不灵活,添加或删除不方便
// 3、需求变更频繁时,很难修改。 装饰器模式生成的子类,功能互不影响