Definition
When an object's state changes, all objects that depend on it are notified.
Realization
Ideas:
- Designate the publisher;
- Add a cache list to the publisher to store the callback function to notify the subscriber;
- When the message is finally published, the publisher will traverse the cache list and trigger the stored subscriber callback function in turn.
example:
// Publishing class
class Subject {
// A cached list of callbacks to notify subscribers
private observers: Observer[] = new Array<Observer>()
private state: number
// New subscribers
public subscribe (observer: Observer): void {
this.observers.push(observer)
}
// Change status, notify subscribers
public setState(state: number): void {
console.log(`Warning: State changed: ${state}`)
this.state = state
this.publish()
}
// Get status
public getState(): number {
return this.state
}
// Publishing events
public publish (): void {
for (let observer of this.observers) {
observer.update()
}
}
// Unsubscribe
public unsubscribe (observer?: Observer): void {
// If no parameter is passed, clear the subscriber
if (!observer) {
this.observers = new Array<Observer>()
} else {
this.observers.splice(this.observers.indexOf(observer), 1)
}
}
}
// Subscriber abstract class
abstract class Observer {
// Subscribed content
protected subject: Subject
// Subscription updates
public abstract update (): void
}
class AObserver extends Observer {
// Subscription in constructor
public constructor (subject: Subject) {
super()
this.subject = subject
this.subject.subscribe(this)
}
public update() {
console.log(`AObserver: ${this.subject.getState()}`)
}
}
class BObserver extends Observer {
// Subscription in constructor
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 Unsubscribe')
subject.unsubscribe(aObserver)
console.log('State change: 150')
subject.setState(150)
console.log('=========')