Javascript设计模式与开发实践:读书笔记3 单例模式

单例模式的定义是:保证一个类仅有一个实例,并提供一个访问它的全局访问点。

基础单例

手写了个简单例子,这个例子很简单,利用的惰性函数特性。

在第一次请求的时候,将自己所有的方法覆盖原先的方法,这样,在第一次请求get的时候。

我们会new一个新的getInstance,并且重置了this的原型链。这样在后续就永远不会再次创建新的getInstance了。

var getInstance = function (value){
    this.value = value;
}
getInstance.prototype.getValue = function () {
    return this.value;
}
getInstance.prototype.get = function (value) {
    this.value = value;
    return this;
}

getInstance.get = function(value){
    Object.assign(this,new getInstance(value))
    return this;
}
var a = getInstance.get('a')
var b = getInstance.get('b')
console.log(a===b);

>> true

透明单例

透明单例的意思,也就是使用者还是按照普通的new去生成一个类,但是,无论这个类new几次,最终返回给使用者的用户都是相同的一个类。

var CreateInstance = (function(){
    var instance;
    var CreateFn = function(value){
        if(instance){
            return instance;
        }        
        return instance = this;

    }
    return CreateFn
})()
var a = new CreateInstance('a')
var b = new CreateInstance('b')
console.log(a===b);

>> true

透明单例在创建的时候,就已经做好了唯一的实例,后续都是使用同一个instance

用代理实现单例模式

代理模式是抽取的创建的真正实体方法,保留了创建流程。代理类仅负责管理单例对象。

var ProxyInstance = (function(){
    var instance;
    return function(value){
        if(!instance){
            instance = new CreateInstance(value);
        }        
        return instance;
    }
})()

var a = new CreateInstance('a')
var b = new CreateInstance('b')
console.log(a===b);

>> true

小结

单例是一种简单的模式,理解单例可以帮助你理解闭包高阶函数的概念。

摄影爱好者,全栈工程师,游戏玩家,积木苦手,超穷手办收藏爱好者

发表评论