-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdesign.js
65 lines (63 loc) · 1.34 KB
/
design.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
/**
* 常见的设计模式 Design pattern
*
*/
// 观察者模式
class Event {
constructor() {
this.callbacks = {};
}
$on(name, fn) {
(this.callbacks[name] || (this.callbacks[name] = [])).push(fn);
}
$emit(name, args) {
let cbs = this.callbacks[name];
if (cbs) {
cbs.forEach(v => {
v.call(this, args);
});
}
}
$off(name) {
this.callbacks[name] = null;
}
}
let event = new Event();
event.$on('event1', function (arg) {
console.log('event1', arg)
})
event.$on('event1', function (arg) {
console.log('又event1', arg)
})
event.$on('event2', function (arg) {
console.log('event2', arg)
})
event.$emit('event1', '欢迎');
event.$emit('event2', '世界');
// 单例模式
function getSingle(fn) {
let result;
return function () {
return result || (result = fn.apply(this, arguments))
}
}
// 策略模式 增加扩展性/表单验证
let strategy = {
"S": function (salary) {
return salary * 3;
},
"A": function (salary) {
return salary * 2;
},
"B": function (salary) {
return salary;
}
}
let calculate = function (level, salary) {
if (level in strategy) {
return strategy[level](salary)
}
return 1;
}
// 中介者模式
// 装饰器模式/代理模式