【学习发布订阅模式】

发布订阅模式

发布订阅模式(Publish-Subscribe Pattern)是一种常见的设计模式,用于实现消息的发布和订阅。在这种模式中,发布者发布消息,而订阅者则订阅感兴趣的消息,并在消息发布时接收通知。

特点
  • 解耦:发布者和订阅者之间是松耦合的关系,彼此不需要知道对方的具体实现细节。这有助于提高系统的灵活性和可扩展性。
  • 实时通信:支持实时消息传递,对于需要及时更新的应用场景非常有用,如实时数据监控、警报系统等。
  • 多对多通信:一个发布者可以向多个订阅者发送消息,同时一个订阅者也可以订阅多个发布者的消息,实现了多对多的通信。
  • 可扩展性:易于扩展,新的订阅者可以随时加入,而不需要修改现有系统的结构。
  • 消息过滤:订阅者可以根据自己的需求订阅特定类型的消息,实现消息的过滤和个性化。
  • 异步处理:发布者发送消息后不需要等待订阅者的处理结果,可以继续其他工作,提高了系统的效率。
JS简单实现
class EventPush {
    constructor(props) {
        this.observer = {}
    }
    publish(name, fn) {
        if (!this.observer[name]) {
            this.observer[name] = []
        }
        console.log('订阅事件', name, fn.name)
        this.observer[name].push(fn);
    }
    notice(name, ...reset) {
        if (!this.observer[name]) {
            console.log('为订阅当前事件!')
            return;
        }
        this.observer[name].forEach(f => f(...reset))
    }
    unsubscribe(name, fn) {
        if (!this.observer[name]) {
            console.log('未订阅当前事件!')
            return;
        }
        const index = this.observer[name].findIndex(f => f == fn);
        if (index != -1) {
            this.observer[name].splice(index, 1)
        }
    }
}

const eventsP = new EventPush();
function say(...reset) {
    console.log('say', reset)
}
eventsP.publish('say', say)
eventsP.publish('say', function (...reset) { console.log('ddd', reset) }) // 匿名函数无法取消
eventsP.notice('say', 'zhangsan')
eventsP.unsubscribe('say', say) // 具名函数可以取消订阅
eventsP.notice('say', 'zhangsan')

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值