单例模式
Indomite
# 单例模式
单一实例模式:一个构造函数只能有一个实例,不管new多少次都只有一个实例
应用:自定义弹出层
/**核心方法:
let instance = null
funcition signleton(){
if(!instance)
instance = 实例对象
return instance
}
**/
function Person() {
this.name = 'Jeck'
}
let instance = null
function signleton(){
if(!instance)
instance = new Person()
return instance
}
const p1 = signleton()
const p2 = signleton()
console.log(p1,p2);
console.log(p1 === p2);
const Person = (function() {
function Person() {
this.name = 'Jeck'
}
Person.prototype.sayHi = function() {
console.log('hello');
}
let instance = null;
return function signleTon(){
if(!instance)
instance = new Person()
return instance
}
})()
const p1 = new Person()
const p2 = new Person()
console.log(p1,p2);
console.log(p1 === p2);
# 观察者模式
监控对象的状态,一旦状态发生改变,马上触发技能
class Publisher {
constructor() {
// 观察者
this.list = []
}
// 添加观察者
addListener(listener) {
this.list.push(listener)
}
// 移除观察者
removeListener(listener) {
this.list.forEach((item, index) => {
if (listener === item) {
this.list.splice(index, 1)
}
})
}
// 触发所有观察者的技能
notify(obj) {
this.list.forEach((item) => {
item.process(obj)
})
}
}
class Subscriber {
process(obj) {
console.log(obj.name)
}
}
# 发布订阅模式
当对象发生变化时,第三方通知监督者,触发技能
class EventEmitter {
constructor() {
this.list = {}
}
on(name, fn, type = 1) {
if (!this.list[name]) {
this.list[name] = []
}
this.list[name].push([fn, type])
}
once(name, fn, type = 0) {
this.on(name, fn, type)
}
emit(name, ...args) {
let fns = this.list[name]
if (!fns || fns.length === 0) return
fns.forEach((fn, index) => {
fn[0].apply(this, args)
if (fn[1] === 0) {
fns.splice(index, 1)
}
})
}
remove(name, func) {
let fns = this.list[name]
if (!fns) {
this.list[name] = []
}
fns.forEach((fn, index) => {
if (fn[0] === func) {
fns.splice(index, 1)
}
})
}
}
let bus = new EventEmitter()
bus.on("click", (value) => {
console.log(value)
})
bus.emit("click", 111)