发布订阅模式和观察者模式的简单实现

259 阅读1分钟

发布订阅模式和观察者模式的简单实现

发布订阅模式

    // 初始化事件调度中心
    class PubSub {
        constructor() {
            this.events = {}
        }

        // 发布功能
        publish(type, ...args) {
            if(this.events[type] && this.events[type].length > 0) {
                this.events[type].forEach(cb => cb(...args))
            }
        }

        // 订阅功能
        subscribe(type, cb) {
            this.events[type] = this.events[type] || []
            this.events[type].push(cb)
        }

        //  取消订阅
        cancleSubscrible(type, cb) {
            if(!Array.isArray(this.events[type]))return
            const index = this.events[type].findIndex(item => item === cb)
            this.events[type].splice(index,1)
            
            if(this.events[type].length === 0)delete this.events[type]
        }
    }

    const pubSub = new PubSub()
    const handleClick = function() {
        console.log('触发了点击事件');
    }
    pubSub.subscribe('click',handleClick)
    pubSub.publish('click')

观察者模式

    // 目标对象(被观察者)类
    class Subject {
        constructor() {
            this.observers = []
        }

        // 添加观察者
        addObserver(observer) {
            this.observers.push(observer)
        }

        // 移除观察者
        removeObserver(observer) {
            const index = this.observers.findIndex(item => item == observer)
            this.observers.splice(index, 1)
        }

        // 通知观察者
        notifyObserver() {
            this.observers.forEach(item => {
                item.update()
            })
        }
    }

    // 观察者类
    class Observer {
        constructor(name, age) {
            this.name = name
            this.age = age
        }
        // 更新方法
        update() {
            console.log(`我是${this.name},${this.age}岁`);
        }
    }

    // 实例化目标对象
    const subject = new Subject()

    // 实例化观察者对象
    const p1 = new Observer('zhangsan', 20)
    const p2 = new Observer('lisi',22)

    subject.addObserver(p1)
    subject.addObserver(p2)

    subject.notifyObserver()

总结

观察者模式和发布订阅模式都是定义一对多的依赖关系,发布订阅模式相比于观察者模式多了一个事件调度中心,耦合度更低,观察者模式是目标对象维护所有的观察者列表