单例模式

为什么要用单例模式

一个项目中有一个登录按钮,点击按钮会弹出一个登录框,无聊点击多少次登录按钮,只会弹出一个登录框,不会频繁的增加和删除,所以单例模式可以最大的复用提高性能。

什么是单例模式

单例模式就是在系统中只有一个实例,无论创建多少次只有一个实例,频繁创建的时候会复用第一次创建的实例。就相当于是一个全局变量。

单例模式🌰

1、一个对象就是一个单例,可用于管理模块

let singleObj = {
    name:'loser',
    age:18,
    getAge:function(){
        return this.age;
    }
}

2、构造函数方式创建单例模式

function Singleton(name){
    this.name = name
}
Singleton.getInstance = function(name){
    if(!this.instance){
        this.instance = new Singleton()
    }
    return this.instance;
}
var a = Singleton.getInstance('a')
var b = Singleton.getInstance('b') 

//例子2
var mySingleton=(function(){
           //构造器函数
           function singleton(options){
               options=options || {}
               this.name='SingletonTestor';
               this.pointX=options.pointX || 6
               this.pointY=options.pointY || 10;
           }
          function init(){
            let now=new Date() //私有方法
            this.name='公共的属性'
            this.getISODate()=function(){
                return now.toISOString();
            }
          }
           //缓存单例的变量
           var instance;
           var _static={
               name:'SingletonTestor',
               getInstance:function(options){
                   if(!instance){
                       instance=new singleton(options)
                   }
                   return instance
               }
           }

           return _static
        })()
        var singletonTest=mySingleton.getInstance({
            pointX:5,
            pointY:5
        })
        console.log(singletonTest)
        var singletonTest1=mySingleton.getInstance({
            pointX:10,
            pointY:10
        })

3、es6方式

class Single{
    constructor(name){
        this.name = name;
        this.instance = null;
    }
    static getInstance(name){
        if(!this.instance){
            this.instance = new Single(name);
        }
        return this.instance;
    }
}

console.log(Single.getInstance('test'))

let test2=Single.getInstance('test2')
console.log(d)

4、闭包版本

function  StorageBase(){
    StorageBase.prototype.getItem=function(){
        return  localStorage.getItem(key)
     }
    StorageBase.prototype.setItem=function(){
        return  localStorage.setItem(key,value)
    }
}
const  Storage1=(function(){
  let instance=null
  return  function (){
      if(!instance){
         instance=new StorageBase()
       }  
        return instance
   }
})()
const storage3=new Storage1()
console.log(storage3)
const storage2=new Storage1()
storage3.setItem('name','张三')
storage3.getItem('name') //张三
storage2.getItem('name')//张三

应用场景

  • 购物车

  • 登录框

  • 命名空间

  • vuex、vue-router

实例:全局数据存储对象 (vuex)

function store(){
  if(store.instance){
      return store.instance
  }
  store.instance=this
}

//同
function store(){
  if(!(this instanceof store)){
      return new store()
  }
}

上面得代码 可以new 也可以直接使用 ,这里使用了一个静态变量instance来记录是否有进行过实例化,如果实例化了就返回这个实例,如果没有实例化说明使第一次调用,就会把this赋给这个静态变量,因为是使用new 调用,这时候得this指向得就是实例化出来得对象,并且最后会隐式得返回this

var  a=new store()
var b=store()
a==b

Last updated

Was this helpful?