JS中设计模式有很多种,单例模式,组合模式,观察者模式,中介者模式,命令模式…今天就先看看其中的几种
单例模式
function Person() {
this.name = 'Jack'
}
//全局
var instance = null
function singleton() {
if (instance === null) {
instance = new Person()
}
return instance
}
var p1 = singleton()
var p2 = singleton()
//p1 和 p2 得到的都是第一次执行的时候的 实例
console.log(p1 === p2)//true
组合模式
//一个构造函数的启动方式
class Play {
constructor () {}
//这个构造函数的启动方法
init () {
console.log('开始玩游戏')
this.a()
this.b()
this.c()
}
a () {}
b () {}
c () {}
}
//第二个构造函数
class Eat {
constructor () {}
init () {
console.log('去吃饭')
}
}
class Sleep {
constructor () {}
init () {
console.log('去睡觉')
}
}
//组合模式的代码
class Compose {
constructor () {
//用来承载每一个实例的数组
this.composeArr = []
}
//向数组里面添加内容
add (instance) {
this.composeArr.push(instance)
}
//把数组里面的每一个内容调用了
init () {
console.log('总开关启动了')
this.composeArr.forEach(item => item.init())
}
}
var c = new Compose()//c 就是一个总开关
//每一次执行 add 方法就是向总开关上添加内容
c.add(new Play())
c.add(new Eat())
c.add(new Sleep())
//只要总开关一启动,里面的每一个构造函数就同时都启动了
c.init()
console.log(c)
观察者模式
观察者模式又称 发布/订阅 模式。
class Observer {
constructor () {
//准备的消息盒子
this.message = {}
}
//订阅的方法 on
on (type, fn) {
//向消息盒子里面添加成员
//type 事件类型, fn 事件处理函数
if (!this.message[type]) {
//表示 this.message 里面没有这个成员
//没有就创建,有的话直接push
this.message[type] = []
}
this.message[type].push(fn)
}
//取消订阅的方法 off
off (type, fn) {
//先判断有没有要取消的方法,有的话取消,没有就不操作
if (!this.message[type]) return
this.message[type] = this.message[type].filter(item => item !== fn)
}
//发布的方法 emit
emit (type) {
//执行消息盒子里面的某一个对应的处理函数
//判断你有没有订阅过, 如果没有订阅过, 直接return
if (!this.message[type]) return
this.message[type].forEach(item => item())
}
}
//将来使用的时候
var o = new Observer()
//订阅事件
o.on('click', handlerA)
o.on('click', handlerB)
//取消订阅事件
o.off('click', handlerA)