设计模式之单例模式

110 阅读1分钟
定义:单例就是保证一个类只有一个实例。实现方法一般是先判断实例存在与否,存在直接返回,不存在了就创建了返回。JavaScript中,单例作为一个命名空间提供者,从全局命名空间里提供一个唯一的访问点来访问该对象实现。

一、构造函数

var Singleton = function(name) {
    if (typeof Singleton.instance === 'object'){
        return Singleton.instance
    }
    this.name = name;
    Singleton.instance = this;
    return this
}
var a = Singleton('sven1');
var b = Singleton('sven2');
console.log(a === b);

二、es6 class

class Singleton {
    constructor(name) {
        this.name = name;
        this.instance = null;
    }
    
    // 构造一个约定俗成的接口getInstance
    static getInstance(name) {
        if(!this.instance) {
            this.instance = new Singleton(name);
        }
        return this.instance;
    }
}
var a = Singleton.getInstance('sven1');
var b = Singleton.getInstance('sven2');
console.log(a === b);

三、闭包

var SingletonTester = (function(){    
    // 构造器函数    
    function Singleton(options){        
        options = options || {};        
        this.name = 'SingletonTester';        
        this.pointX = options.pointX || 6;        
        this.pointY = options.pointY || 10;    
    }        
    // 缓存单例的变量    
    var instance;    
    // 静态变量和方法    
    var _static = {        
        name: 'SingletonTester',        
        getInstance: function(options) {            
            if (instance === undefined) {                
                instance = new Singleton(options);            
            }            
            return instance;        
        }    
    };    
    return _static;
})();
var singletonTest = SingletonTester.getInstance({    pointX: 5,    pointY: 5})
console.log(singletonTest.pointX); // 5
console.log(singletonTest.pointY); // 5
var singletonTest1 = SingletonTester.getInstance({    pointX: 10,    pointY: 10})
console.log(singletonTest1.pointX) // 5
console.log(singletonTest1.pointY) // 5