发布订阅者模式
/**
* 作为发布-订阅模式的中间人
*
* @class Event
*/
class Event {
constructor() {
this.subscribers = []; // 订阅者
this.messages = []; // 发布信息
}
publish(message) {
this.messages.push(message);
// 将所有发布信息传给订阅者
this.subscribers.forEach(sub => sub(this.messages));
}
subscribe(fn) {
this.subscribers.push(fn);
}
}
const event = new Event();
event.subscribe((messages) => { console.log("1号订阅:" + messages); })
event.subscribe((messages) => { console.log("2号订阅:" + messages); })
event.publish('第一条信息');
event.publish('第二条信息');
观察者模式
/**
*被观察者,一个
*
* @class Object
*/
class Subject {
constructor(name, state) {
this.name = name;
this.state = state || 'default';
this.observers = [];
}
// 被观察者提供一个接收观察者的方法
attach(...observers) {
this.observers.push(...observers);
}
setState(state) {
if (this.state !== state) {
// 状态发生改变
this.state = state;
console.log('当前状态:', state);
}
// 通知每一个观察者,被观察者状态发生改变
this.observers.forEach(ob => ob.update(state));
}
}
/**
*观察者,多个
*
* @class Observer
*/
class Observer {
constructor(name) {
this.name = name;
}
update(state) {
console.log(`${this.name}: state is changed to ${state}`);
}
}
const sub = new Subject('被观察者');
const o1 = new Observer('观察者A');
const o2 = new Observer('观察者B');
sub.attach(o1, o2);
sub.setState('changed')
单例模式
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
实现的方法为先判断实例存在与否,如果存在则直接返回,如果不存在就创建了再返回,这就确保了一个类只有一个实例对象。
class Singleton {
constructor(name) {
this.name = name
this.instance = null
}
// 构造一个接口,用于对该类进行实例化
// 类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。
static getInstance(name) {
if (!this.instance) {
this.instance = new Singleton(name)
} return this.instance
}
}