定義
當一個對象的狀態(tài)發(fā)生改變時惧眠,所有依賴于它的對象都將得到通知疹瘦。
實現(xiàn)
思路:
- 指定發(fā)布者霜定;
- 給發(fā)布者添加一個緩存列表嗤放,用于存放回調(diào)函數(shù)以便通知訂閱者思喊;
- 最后發(fā)布消息的時候,發(fā)布者會遍歷這個緩存列表次酌,依次觸發(fā)里面存放的訂閱者回調(diào)函數(shù)恨课。
例子:
// 發(fā)布類
class Subject {
// 緩存列表,用以存放回調(diào)函數(shù)岳服,以便通知訂閱者
private observers: Observer[] = new Array<Observer>()
private state: number
// 新增訂閱者
public subscribe (observer: Observer): void {
this.observers.push(observer)
}
// 改變狀態(tài)剂公,通知訂閱者
public setState(state: number): void {
console.log(`Warning: State changed: ${state}`)
this.state = state
this.publish()
}
// 獲取狀態(tài)
public getState(): number {
return this.state
}
// 發(fā)布事件
public publish (): void {
for (let observer of this.observers) {
observer.update()
}
}
// 取消訂閱
public unsubscribe (observer?: Observer): void {
// 如果沒傳參數(shù),則清空訂閱者
if (!observer) {
this.observers = new Array<Observer>()
} else {
this.observers.splice(this.observers.indexOf(observer), 1)
}
}
}
// 訂閱者抽象類
abstract class Observer {
// 訂閱的內(nèi)容
protected subject: Subject
// 訂閱更新
public abstract update (): void
}
class AObserver extends Observer {
// 構(gòu)造方法里訂閱
public constructor (subject: Subject) {
super()
this.subject = subject
this.subject.subscribe(this)
}
public update() {
console.log(`AObserver: ${this.subject.getState()}`)
}
}
class BObserver extends Observer {
// 構(gòu)造方法里訂閱
public constructor (subject: Subject) {
super()
this.subject = subject
this.subject.subscribe(this)
}
public update() {
console.log(`BObserver: ${this.subject.getState()}`)
}
}
const subject = new Subject()
const aObserver = new AObserver(subject)
const bObserver = new BObserver(subject)
console.log('========')
console.log('State change: 100')
subject.setState(100)
console.log('========')
console.log('=========')
console.log('aObserver 取消訂閱')
subject.unsubscribe(aObserver)
console.log('State change: 150')
subject.setState(150)
console.log('=========')