观察者模式与发布-订阅者模式

在这里插入图片描述

(1)是什么?

  • 观察者模式:观察者与被观察者直接通信,被观察者发生变化时,会直接通着观察者更新,即调用观察者的一些方法实现观察者的更新操作,是一种一对多的模式。
/*
    观察者模式
    实现:被观察者和观察者分别由两个类表示。
        被观察者类拥有添加观察者实例的方法以及通知观察者更新的方法,
        观察者类拥有更新方法。
**/
function Subject () {
    this.observers = [];
    this.addOb = function(ob) {
        this.observers.push(ob);
    }
    this.notify = function() {
        this.observers.forEach(ob => {
            if (typeof ob.update === 'function') {
                ob.update();
            }
        });
    }
    return this;
}

function Observer(name) {
    this.name = name;
    this.update = function() {
        console.log(this.name + 'update function is triggered');
    }
}

const sub = new Subject();
const ob1 = new Observer('ob1');
const ob2 = new Observer('ob2');

sub.addOb(ob1);
sub.addOb(ob2);
sub.notify();
  • 发布-订阅者模式:发布者和订阅者不会进行直接通信,而是通过一个中间件——事件通道(event channel)来实现二者之间的消息传递,这也是这两种模式之间最大的区别。该模式将消息分为不同的话题(topic),只有订阅的话题发生更新时,订阅者才会接收到更新通知,也是一种一对多的模式。
/*
    发布者-订阅者模式
    定义发布者和订阅者两个类。
    发布者类拥有存储分类主题的对象以及发布和订阅的方法,订阅者类拥有更新的方法。
**/
function Publisher() {
    // 存储分类的主题
    this.topic= {};
    
    // 订阅某个主题
    this.subscribe = function(type, fun) {
        if (!this.topic[type]) {
            this.topic[type] = [];
        }
        this.topic[type].push(fun);
    }
    
    // 发布某个主题的信息
    this.publish = function(type) {
        if (Object.prototype.toString.call(this.topic[type]) === '[object Array]') {
            this.topic[type].forEach(f => f(type));
        }
    }
    
    return this;
}

function Subscriber(type) {
    this.type = type;
    return this;
}

const publisher = new Publisher();
const subcriber1 = new Subscriber('news');
const subcriber2 = new Subscriber('reading');
publisher.subscribe(subcriber1.type, (type) => {
    console.log(type + 'subscribe is update')
});
publisher.subscribe(subcriber2.type, (type) => {
    console.log(type + ' publish is update');
});

publisher.publish('news');
publisher.publish('reading');

在这里插入图片描述

(2)为什么?

  • 观察者模式,被观察者与观察直接通信,所有的通信逻辑均在被观察者对象上,会造成被观察者代码冗余,逻辑复杂。此外,只要被观察者发生更新,无论是不是观察者关注的信息,均会导致观察者触发更新操作。要避免这种情况,就必须的在被观察者内部添加逻辑,从而进一步导致观察者逻辑复杂。
  • 发布者-订阅者模式,其采用中间件(event channel)将发布者与订阅者隔离且联系起来,即在观察者模式的基础上,其将被观察者与观察者进行逻辑上的解耦,更加符合了高内聚低耦合的开发原则。此外,订阅者仅仅会受到相关订阅信息的更新。

(3)怎么用、应用场景?
相关状态管理的方案,均采用了发布者-订阅者的设计模式。如:vuex、redux、dva等。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值