Javascript Singleton Factory

时间:2015-06-18 21:27:28

标签: javascript design-patterns

所以我有一个Singleton" class"效果很好:

function Base_Singleton () {
    if ( Base_Singleton.prototype._singletonInstance )
        return Base_Singleton.prototype._singletonInstance;
    else
        return Base_Singleton.prototype._singletonInstance = this;
}

这很有效。如果需要,可以创建多个实例,它们都反映了彼此的变化:

var sing1 = new Base_Singleton();
var sing2 = new Base_Singleton();
sing1.foo = "bar";
sing2.foo === "bar"; // true

所以我现在想要的是能够使用自己的信息创建多个Singleton接口。我愿意接受任何方式来实现这一目标。想到的两种方法是扩展或制造工厂。

当我尝试扩展时,新对象只获取Base_Singleton的原型,因此它不会扩展它只是创建另一个实例。

我认为最好的方法是通过每次都可以创建新对象的工厂:

var Singleton_Factory = new function () {
    // Let's just assume this is in a web environment
    var global = global || window; 

    /**
     * Build a new object with Singleton functionality.
     * Singleton functionality based from https://goo.gl/YfmiTH
     *
     * The idea is that there is an instance of the object shared through the 
     * singleton's prototype. You can create as many 'new' Singletons as you
     * desire, but they all will mirror the same prototypical object.
     * 
     * @param  {string} singletonName The name of the new Singleton, and its 
     *                                prototype
     * @param  {object} namespace     The namespace to add the new object to
     * 
     * @return {object}               The newly created Singleton
     */
    this.make = function ( singletonName, namespace ) {
        // Default to global object as defined earlier
        namespace = namespace || global;
        // If there is a shared _singletonInstance, return that
        if ( namespace[singletonName].prototype._singletonInstance )
            return namespace[singletonName].prototype._singletonInstance;
        //  If there isn't one, create and return 'this'
        else
            return namespace[singletonName].prototype._singletonInstance = this;
    }
}

问题在于我尝试在未定义的情况下使用prototype

如何创建可以创建功能为Base_Singleton的新原型的工厂?

0 个答案:

没有答案