前端设计模式-单例模式

单例模式
1.确保只能有一个实例
2.可以全局访问
比如全局window,vuex 等都是单例模式的实现

const Singleton = function(name) {
  this.name = name
  this.instance = null
}
// 在方法原型上添加getName()方法
Singleton.prototype.getName = function() {
  console.log(this.name)
}
Singleton.getInstance = function(name) {
  // 如果实例不存在,则实例化一个
  if (!this.instance) { 
    this.instance = new Singleton(name)
  }
  return this.instance
}
// test
const a = Singleton.getInstance('a') // 通过 getInstance 来获取实例
const b = Singleton.getInstance('b')
console.log(a === b)
// ES6实现
//类声明
class Singleton {
//类构造函数
  constructor(name) {
    this.name = name
    this.instance
  }
  // 原型方法
  getName() {
    console.log(this.name)
  }
  // 静态方法
  static getInstance(name) {
    //如果有实例则返回,没有则创建并返回 
    return this.instance || (this.instance = new Singleton(name))
  }
}

总结:1.需要使用return。使用new的时候如果没有手动设置return,那么默认会返回this。但是,我们这里要使得每次返回的实例相同,也就是需要手动控制创建的对象,因此这里需要使用return。
2.我们需要每次return的是同一个对象。也就是说实际上在第一次创建实例的时候,需要把这个实例保存起来。再new下一个实例的时候,直接return这个保存的实例即可。因此,这里需要用到闭包了。

// 用闭包的方式实现:
let instanceClass = function () {}
// 匿名自执行函数
let Instance = (function () {
	// 声明一个instance对象
    let instance // 声明一个instance对象
    return function () {
        if (instance) { // 如果已存在 则返回instance
            return instance
        }
        instance = new instanceClass() // 如果不存在 则new一个instanceClass实例对象
        return instance // 始终返回这个instance
    }
})()
let a = new Instance()
let b = new Instance()
console.log(a===b) // true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值