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
| function EventEmit(){ this._arr = []; }
EventEmit.prototype.on = function(callBack){ this._arr.push(callBack) }
EventEmit.prototype.unon = function(callBack){ this._arr.filter(fn=>{ if(fn !== callBack){ return fn; } }) }
EventEmit.prototype.emit = function(){ this._arr.forEach(fn=>fn.apply(this, arguments)) }
let fn = new EventEmit(); let obj = {};
fn.on(function(data,key){ obj[key] = data; if(Object.keys(obj).length==2){ console.log(obj) } })
fn.emit('张三', 'name' ) fn.emit(18,'age')
|
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
| class Serve { constructor(){ this._arr = [] } attch(callBack){ this._arr.push(callBack) } setState(val){ this._arr.forEach(fn=>{ fn.update(val) }) } }
class Observe { constructor(props){ this.state = props; } update(val){ console.log('name-',this.state, 'datra-',val) } }
let o1 = new Observe('name1') let o2 = new Observe('name2')
let server = new Serve();
server.attch(o1) server.attch(o2)
server.setState('asdfasd')
|
发布/订阅模式和观察者模式的区别在于:
发布订阅模式是发布和订阅相互独立的,耦合度较松;
观察者模式是将观察者耦合到服务内部,消息触发之后会通知/执行观察者的操作;