单例设计模式

  • 单例设计模式的核心
    确保只有一个实例,供全局访问使用
  • 普通对象
let F= function (name) {
    this.name = name;
};
let a = new F("a");
let b = new F("b");
console.log(a===b);  //false

不足之处:
(1)没有封装性,属性和方法都是暴露在外面的
(2)全局变量容易造成命名空间的污染
(3)容易造成对象的浪费

  • 传统的单例
let Singleton = function (name) {
    this.name = name;
    this.instance = null;
};
Singleton.getInstance = function (name) {
    if(!this.instance){
        this.instance = new Singleton(name);
    }
    return this.instance;
};
let c= Singleton.getInstance("c");
let d= Singleton.getInstance("d");
console.log(c===d); //true
  • 用代理实现单例设计模式
let createSingleton = function (name) {
    this.name = name;
    this.say();
};
createSingleton.prototype.say = function () {
    console.log(this.name);
};
let ProxySingletonCreate = (function () {
    let instance = null;
    return function (name) {
        if(!instance) {
            instance = new createSingleton(name);
        }
        return instance;
    }
})();
let e = new ProxySingletonCreate("e");
let f = new ProxySingletonCreate("f");

console.log(e===f); //true
console.log(e); //createSingleton { name: 'e' }
console.log(f); //createSingleton { name: 'e' }

你可能感兴趣的:(单例设计模式)