观察者模式 - 演示与场景

  • 发布&订阅
  • 一对多/一对一
    UML类图:


    观察者模式 - 演示与场景_第1张图片
    image.png

代码演示:

// 主题、保存状态,状态变化之后触发所有观察者模式
class Subject{
    constructor() {
        this.state = 0
        this.observers = []
    }
    getState(){
        return this.state
    }
    setState(state){
        this.state = state
        this.notifyAllObservers()
    }
    notifyAllObservers(){
        this.observers.forEach(observer => {
            observer.update()
        })
    }
    attach(observer){
        this.observers.push(observer)
    }
}
// 观察者
class Observer {
    constructor(name, subject){
        this.name = name
        this.subject = subject
        this.subject.attach(this)
    }
    update(){
        console.log(`${this.name} update, state: ${this.subject.getState()} `)
    }
}

// 测试
let s = new Subject()
let o1 = new Observer('o1', s)
let o2 = new Observer('o2', s)
let o3 = new Observer('o3', s)

s.setState(1)
s.setState(2)
s.setState(3)

使用场景:
网页事件绑定

$('#btn').click(function(){
  console.log(1)
})
$('#btn').click(function(){
  console.log(2)
})
$('#btn').click(function(){
  console.log(3)
})

Promise
三种状态:pending、fulfilled、rejected
jQuery callbacks

// 自定义事件,自定义回调
var callbacks = $.Callbacks()
callbacks.add(function(info){
  console.log('fn1', info)
})
callbacks.add(function(info){
  console.log('fn2', info)
})
callbacks.add(function(info){
  console.log('fn3', info)
})

nodejs自定义事件

你可能感兴趣的:(观察者模式 - 演示与场景)