有人把观察者(Observer)模式等同于发布(Publish)/订阅(Subscribe)模式,也有人认为这两种模式还是存在差异,而我认为确实是存在差异的,本质上的区别是调度的地方不同。
观察者模式
比较概念的解释是,目标和观察者是基类,目标提供维护观察者的一系列方法,观察者提供更新接口。具体观察者和具体目标继承各自的基类,然后具体观察者把自己注册到具体目标里,在具体目标发生变化时候,调度观察者的更新方法。
比如有个“天气中心”的具体目标A,专门监听天气变化,而有个显示天气的界面的观察者B,B就把自己注册到A里,当A触发天气变化,就调度B的更新方法,并带上自己的上下文。
观察者模式与发布/订阅模式区别 - 图1

发布/订阅模式
比较概念的解释是,订阅者把自己想订阅的事件注册到调度中心,当该事件触发时候,发布者发布该事件到调度中心(顺带上下文),由调度中心统一调度订阅者注册到调度中心的处理代码。
比如有个界面是实时显示天气,它就订阅天气事件(注册到调度中心,包括处理程序),当天气变化时(定时获取数据),就作为发布者发布天气信息到调度中心,调度中心就调度订阅者的天气处理程序。
观察者模式与发布/订阅模式区别 - 图2

总结
1. 从两张图片可以看到,最大的区别是调度的地方。
虽然两种模式都存在订阅者和发布者(具体观察者可认为是订阅者、具体目标可认为是发布者),但是观察者模式是由具体目标调度的,而发布/订阅模式是统一由调度中心调的,所以观察者模式的订阅者与发布者之间是存在依赖的,而发布/订阅模式则不会。
2. 两种模式都可以用于松散耦合,改进代码管理和潜在的复用。
附录

观察者模式实现代码(JavaScript版):

  1. //观察者列表
  2. function ObserverList(){
  3. this.observerList = [];
  4. }
  5. ObserverList.prototype.add = function( obj ){
  6. return this.observerList.push( obj );
  7. };
  8. ObserverList.prototype.count = function(){
  9. return this.observerList.length;
  10. };
  11. ObserverList.prototype.get = function( index ){
  12. if( index > -1 && index < this.observerList.length ){
  13. return this.observerList[ index ];
  14. }
  15. };
  16. ObserverList.prototype.indexOf = function( obj, startIndex ){
  17. var i = startIndex;
  18. while( i < this.observerList.length ){
  19. if( this.observerList[i] === obj ){
  20. return i;
  21. }
  22. i++;
  23. }
  24. return -1;
  25. };
  26. ObserverList.prototype.removeAt = function( index ){
  27. this.observerList.splice( index, 1 );
  28. };
  29. //目标
  30. function Subject(){
  31. this.observers = new ObserverList();
  32. }
  33. Subject.prototype.addObserver = function( observer ){
  34. this.observers.add( observer );
  35. };
  36. Subject.prototype.removeObserver = function( observer ){
  37. this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
  38. };
  39. Subject.prototype.notify = function( context ){
  40. var observerCount = this.observers.count();
  41. for(var i=0; i < observerCount; i++){
  42. this.observers.get(i).update( context );
  43. }
  44. };
  45. //观察者
  46. function Observer(){
  47. this.update = function(){
  48. // ...
  49. };
  50. }

发布/订阅模式实现代码(JavaScript经典版):

  1. var pubsub = {};
  2. (function(myObject) {
  3. // Storage for topics that can be broadcast
  4. // or listened to
  5. var topics = {};
  6. // An topic identifier
  7. var subUid = -1;
  8. // Publish or broadcast events of interest
  9. // with a specific topic name and arguments
  10. // such as the data to pass along
  11. myObject.publish = function( topic, args ) {
  12. if ( !topics[topic] ) {
  13. return false;
  14. }
  15. var subscribers = topics[topic],
  16. len = subscribers ? subscribers.length : 0;
  17. while (len--) {
  18. subscribers[len].func( topic, args );
  19. }
  20. return this;
  21. };
  22. // Subscribe to events of interest
  23. // with a specific topic name and a
  24. // callback function, to be executed
  25. // when the topic/event is observed
  26. myObject.subscribe = function( topic, func ) {
  27. if (!topics[topic]) {
  28. topics[topic] = [];
  29. }
  30. var token = ( ++subUid ).toString();
  31. topics[topic].push({
  32. token: token,
  33. func: func
  34. });
  35. return token;
  36. };
  37. // Unsubscribe from a specific
  38. // topic, based on a tokenized reference
  39. // to the subscription
  40. myObject.unsubscribe = function( token ) {
  41. for ( var m in topics ) {
  42. if ( topics[m] ) {
  43. for ( var i = 0, j = topics[m].length; i < j; i++ ) {
  44. if ( topics[m][i].token === token ) {
  45. topics[m].splice( i, 1 );
  46. return token;
  47. }
  48. }
  49. }
  50. }
  51. return this;
  52. };
  53. }( pubsub ));