liuyingbin19222 / leetcode_training

leetcode
0 stars 0 forks source link

单例模式-js #5

Open liuyingbin19222 opened 4 years ago

liuyingbin19222 commented 4 years ago

单例模式可以不需要调用类方法的时候每次都要实例化这一个类对象,单例模式使用的是同一个对象。 单例模式只允许实例化一次类对象。

/*
    lodash: before.js 
    创建一个调用func的函数,并绑定this和创建的函数的arguments对象,并且调用次数少于n次,创建的函数返回最后一次对func的调用。

*/

function test(){
    console.log('this is test函数');
}

function mybefore(n,func){
    let result ;
    if(typeof func !== 'function'){
        throw new TypeError("请输入函数");
    }
    return function(...args){
        if(--n > 0){
            result = func.apply(this,args);
        }
        if(n <= 1){
            return undefined;
        }
        return result;
    }
}

function myonce(func){
    return mybefore(2,func);
}

const _myonce = 
myonce(test);   // 注意要实例化对象;

_myonce();
_myonce();

单例模式可以保证一个类只有一个实例,并提供全局访问的节点; 实现思路:可以在类中定义一个状态变量,当第一次实例化的时候,记录状态,后面每一次调用都使用第一次实例化的对象;

class oneDog{
    constructor(name){
        this.name = name;
    }
    show(){
        console.log("单例对象");
    }
    static Instance(){
        if(!oneDog.instance){
            oneDog.instance = new oneDog();
        }
        return oneDog.instance;
    }
}

const myonedog = oneDog.Instance();
const mytowdog = oneDog.Instance();

console.log("判读是否是同一个对象:",  myonedog == mytowdog);

Instance函数可以使用闭包来实现:

oneDog.Instance = (function(){
    let instance ;
    return function(){
        if(!instance){
            instance = oneDog.Instance();
        }
        return instance;
    }
})();

在vuex中也应用到了单例模式, vuex中各个组件共享同一个store变量; 在vue中使用vue.use(vuex)来调用vuex; vuex 的实现思路:

let Vue // 这个Vue的作用instance作用一样
...

export function install (_Vue) {

  if (Vue && _Vue === Vue) {  //判读_vue是否被install过;
    if (process.env.NODE_ENV !== 'production') {
      console.error(
        '[vuex] already installed. Vue.use(Vuex) should be called only once.'
      )
    }
    return
  }

  Vue = _Vue; // 没有install的话,赋值;
  applyMixin(Vue); // 将vuex用到vue中;
}

面试题: 实现storage , 基于localStorage进行封装;

class Storage{
    static Instance(){
        if(!Storage.instance){
            Storage.instance = new Storage();
        }
        return Storage.instance;
    }
    setItem(key,value){
        return localStorage.setItem(key,value);
    }
    getItem(key){
        return localStorage.getItem(key);
    }
}

const storage1 = Storage.Instance();
const storage2 = Storage.Instance();

storage1.setItem("name","jiji");

storage1.getItem("name");
storage2.getItem("name");

实例化多个对象,本质是实例化一次。 这样不会能造成Storage的混乱。

liuyingbin19222 commented 4 years ago

对于Storage.Instance() , 同样可以使用闭包来实现