Skip to content

Latest commit

 

History

History
66 lines (56 loc) · 1.46 KB

08.md

File metadata and controls

66 lines (56 loc) · 1.46 KB

js 面向对象初接触(8)

行为型 - 观察者模式

观察者模式定义

定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。

观察者模式何时使用

  1. 一个对象的改变将导致其他一个或多个对象也发生改变,而不知道具体有多少对象将发生改变,可以降低对象之间的耦合度。

代码模拟

  1. update: 发布方法
  2. subscribe:订阅方法
  3. unsubscribe: 取消订阅
function Observer() {
    this.fns = [];
}
Observer.prototype = {
    // 注册
    subscribe: function (fn) {
        this.fns.push(fn);
    },
    // 取消注册
    unsubscribe: function (fn) {
        console.log(fn)
        this.fns = this.fns.filter(
            function (el) {
                if (el !== fn) {
                    return el;
                }
            }
        );
    },
    // 发布
    update: function (o, thisObj) {
        var scope = thisObj || window;
        this.fns.forEach(
            function (el) {
                el.call(scope, o);
            }
        );
    }
};

//测试
var o = new Observer;
var f1 = function (data) {
    console.log('Robbin: ' + data + ', 赶紧干活了!');
};

var f2 = function (data) {
    console.log('Randall: ' + data + ', 加点工资了!');
};

o.subscribe(f1);
o.subscribe(f2);

o.update("Tomz")

//退订f1
o.unsubscribe(f1);
//再来验证
o.update("Tomz");