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!');
  • 相关阅读:
    C++模板进阶指南:SFINAE
    SFINAE and enable_if
    Effective Modern C++:05右值引用、移动语义和完美转发
    C++左值和右值
    Effective Modern C++:04智能指针
    Effective Modern C++:03转向现代C++
    Effective Modern C++:02auto
    Effective Modern C++:01类型推导
    c++ vitual继承
    c++正确处理 is-a has-a关系
  • 原文地址:https://www.cnblogs.com/dudeyouth/p/9467672.html
Copyright © 2011-2022 走看看