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!');
  • 相关阅读:
    相关书籍下载2
    神奇的null和undefined
    相关书籍下载1
    微信小程序之for循环
    渐变(Gradients)
    模拟今日头条顶部导航菜单
    网格布局之相关特性
    网格布局之合并单元格
    网格布局
    Linux常用命令
  • 原文地址:https://www.cnblogs.com/dudeyouth/p/9467672.html
Copyright © 2011-2022 走看看