JavaScript 观察者模式

127 阅读1分钟

一种 发布 & 订阅 的概念
当对象间存在一对多的关系的时候,当一个对象的状态发生变化,所有依赖于它的对象都会得到通知并被触发更新。

简单来说就是,你在网上订了一个东西,然后你就可以做你其他的事情了,等你订得物品到了,快递员会通知你去拿,或者直接送到你手上。

观察者模式,其实在开发中有很多,比如 事件监听、watch、promise等


class Theme {
    constructor() {
        this.status = 0
        this.observers = []
    }
    
    getStatus() {
        return this.status
    }
    
    setStatus(val) {
        if(this.status != val) {
            this.status = val
            this.observersUpdate()
        }
    }
    
    observersUpdate() {
        this.observers.forEach(item => {
            item.update()
        })
    }
    
    addObserver(observer) {
        this.observers.push(observer)
    }
}

class Observer {
    constructor(name, theme) {
        this.name = name
        this.theme = theme
        this.theme.addObserver(this)
    }
    
    update() {
        console.log(`${this.name}更新, status: ${this.theme.getStatus()}`)
    }
}

const theme = new Theme()

const observer1 = new Observer('1', theme)
const observer2 = new Observer('2', theme)
const observer3 = new Observer('3', theme)

theme.setStatus(1)