设计模式”(Design Pattern)是针对编程中常常出现的、具备共性的问题,所提出的解决方法。著名的《设计模式》一书一共提出了23种模式。编程
它定义了一种对象间一对多的关系,多个订阅者对象将本身的“主题/事件”注册进一个目标对象,当目标对象状态发生改变时,只须要去执行对应订阅者注册的 "主题/事件" 就好了。这是一种松耦合的状态。目标对象不用关心任何订阅者的状况, 只须要发布注册在本身身上的事件就好了。
订阅者只管注册 目标对象只管发布 互不影响
代码实现:设计模式
let event = { clientList: {}, listen (key, fn) { if (!this.clientList[key]) { this.clientList[key] = [] } this.clientList[key].push(fn) // 订阅的消息添加进缓存列表 }, trigger (type, money) { let fns = this.clientList[type] if (!fns || fns.length === 0) { // 若是没有绑定对应的消息 return false } fns.forEach(fn => { fn.apply(this, [money]) }) } } // 再定义一个installEvent函数,用于给全部对象动态安装发布-订阅功能 // 如:另外一家售楼处也想要这个功能,就能够调用这个注册了,不用再写多一次这段代码 let installEvent = obj => { for (let i in event) { obj[i] = event[i] } } // 给售楼处对象salesOffices动态增长发布-订阅功能 let salesOffices = {} installEvent(salesOffices) // 小明订阅信息 salesOffices.listen('squareMeter88', price => { console.log('小明,你看中的88平方的房子,价格=' + price) }) // 小光订阅信息 salesOffices.listen('squareMeter88', price => { console.log('小光,你看中的88平方的房子,价格=' + price) }) // 小红订阅信息 salesOffices.listen('squareMeter100', price => { console.log('小红,你看中的100平方的房子,价格=' + price) }) salesOffices.trigger('squareMeter88', 2000000) salesOffices.trigger('squareMeter100', 2500000)
观察者模式与发布订阅最大的区别是订阅者注册的是本身自己,再也不是注册 “主题/事件”,当目标对象状态发生改变时,会调用自身的通知方法,从而调用注册在自身的订阅者的更新方法。缓存
//观察者列表 function ObserverList(){ this.observerList = []; } ObserverList.prototype.add = function( obj ){ return this.observerList.push( obj ); }; ObserverList.prototype.count = function(){ return this.observerList.length; }; ObserverList.prototype.get = function( index ){ if( index > -1 && index < this.observerList.length ){ return this.observerList[ index ]; } }; ObserverList.prototype.indexOf = function( obj, startIndex ){ var i = startIndex; while( i < this.observerList.length ){ if( this.observerList[i] === obj ){ return i; } i++; } return -1; }; ObserverList.prototype.removeAt = function( index ){ this.observerList.splice( index, 1 ); }; //目标 function Subject(){ this.observers = new ObserverList(); } Subject.prototype.addObserver = function( observer ){ this.observers.add( observer ); }; Subject.prototype.removeObserver = function( observer ){ this.observers.removeAt( this.observers.indexOf( observer, 0 ) ); }; Subject.prototype.notify = function( context ){ var observerCount = this.observers.count(); for(var i=0; i < observerCount; i++){ this.observers.get(i).update( context ); } }; //观察者 function Observer(){ this.update = function(){ // ... }; }
发布订阅模式实现了更细粒度化的管理,观察者模式当目标对象状态变化时会通知全部订阅者,而发布订阅则会经过调度中心执行具体的订阅者注册的 "主题/事件",发布订阅更松耦合一些。app