单例模式
保证一个类只有一个实例,一般先判断实例是否存在,如果存在直接返回,不存在则先创建再返回,这样就可以保证一个类只有一个实例对象。
作用:
(1)、保证某个类的对象的唯一性; (2)、模块间通信;
(3)、防止变量污染
class SingleObject {
login() {
console.log('login...')
}
}
SingleObject.getInstance = (function () {
let instance
return function () {
if (!instance) {
instance = new SingleObject();
}
return instance
}
})()
发布订阅模式
发布者-订阅者模式又称观察者模式:当一个对象(发布者)状态发生改变时,所有依赖它的对象(订阅者)都会得到通知
class Sub{
constructor(){
// 收集订阅信息,调度中心
this.list = {}
}
// 订阅
on(name,userId,fn){
if(!(this.list[name] instanceof Array)){
this.list[name] = []
}
this.list[name].push({userId,fn})
}
// 发布
emit(name,content){
this.list[name].forEach(item=>{
item.fn(content)
})
}
// 取消订阅
off(name,userId){
this.list[name].forEach((item,index)=> {
if(item.userId === userId){
this.list[name].splice(index,1)
}
})
}}
let sub = new Sub();