zoukankan      html  css  js  c++  java
  • 观察者模式与发布订阅者模式的区别

    两者区别简述:

    1.  发布订阅模式是最常用的一种观察者模式的实现,并且从解耦和重用角度来看,更优于典型的观察者模式

    2. 订阅者有调度中心

    观察者模式:

     发布订阅模式:

     

     代码实现上的区别:

    // 观察任意数组的push操作
    let array = { watch(target, callback) { if (target instanceof Array) { let push = target.push; let _this = this; Object.defineProperty(target, "push", { writable: true, enumerable: false, configurable: true, value: function(exponent) { callback.apply(_this, arguments); push.apply(target, arguments); } }) } } } var arr = [1, 2, 3, 4, 5];
    array.watch(arr,
    function(value) { console.log('push :', [].slice.call(arguments)) }); arr.push(6, 7); console.log(arr);
    var arr1 = [8, 9]; array.watch(arr1, function(value) { console.log('push :', [].slice.call(arguments)) }); arr1.push(10, 11); console.log(arr1);

    // 订阅者与发布 class Subscriber { constructor() { this.list = []; } // 订阅 subscribe(name, callback) { if (typeof callback !== "function") { throw new Error('subscribe method param2:callback is not a function'); return false; } if (this.list[name] && this.list[name] instanceof Array) { this.list[name].push(callback); } else { this.list[name] = [callback]; } } // 发布 release(name, data) { if (typeof this.list[name] === "undefined") { throw new Error(name + ' event is undefined!'); } else { this.list[name].forEach((callback) => { typeof callback === "function" && callback.call(this, data); }); } } } // 实例化线人 let my = new Subscriber(); my.subscribe('eventName', (data) => { console.log(data); }); my.release('eventName','doing something!');
  • 相关阅读:
    [JZOJ3386] 守卫者的挑战
    [JZOJ3385] 黑魔法师之门
    [JZOJ3383] 太鼓达人
    [JZOJ3382] 七夕祭
    NOIP模拟测试on 2019.9.27
    数据结构测试2 on 2019.9.25
    数据结构测试1 on 2019.9.24
    P2047 [NOI2007]社交网络
    P2286 [HNOI2004]宠物收养场
    P1342 请柬 建反图+dijkstra
  • 原文地址:https://www.cnblogs.com/dudeyouth/p/9467672.html
Copyright © 2011-2022 走看看