单例模式
单例模式是一种设计模式,指在确保一个类只有一个实例,并提供一个全局访问点来访问该实例;
前端对于单例模式不常用,但是单例的思想无处不在;
创建之后缓存以便继续使用;
如:弹窗、遮罩层、登录框、vuex redux 中的 store
TypeScript
禁止外部实例化:private constructor
获取单例:static getInstance
class Singleton{name: stringprivate constructor(name: string) {this.name = name}private static insatance: Human | null // 单例对象static getInstance(name: string): Human {if (Human.insatance == null) {Human.insatance = new Singleton(name)}return Human.insatance}
}
返回单例:
const p1 = Singleton.getInstance('a')
const p2 = Singleton.getInstance('b') // 返回p1
console.log(p1 === p2) // true
JavaScript
使用闭包
function genGetInstance() {let instance // 闭包class Singleton{}return () => {if (instance == null) {instance = new Singleton()}return instance}
}const getInstance = genGetInstance()
const s1 = getInstance()
const s2 = getInstance()
console.log(s1 === s2) // true
模块化实现: ~ 创建单独的 js 文件
let instance
class Singleton{}
export default () => {if (instance == null) {instance = new Singleton}return instance
}