Войти с помощью github
Форум /
5 years ago

singleton

Please kick me!

demo

/* global modules:false */
modules.define('singleton', ['inherit'], function (provide, inherit, Singleton) {

    /**
     * @abstract
     * @class Singleton
     */
    Singleton = inherit( /** @lends Singleton.prototype */ {

        /**
         * Must be implemented by subclass
         * @constructor
         * @private
         */
        __constructor: function () {}


    }, /** @lends Singleton */ {

        /**
         * Instance stores a reference to the Singleton
         * @private
         */
        _instances: [],

        /**
         * Get the Singleton instance if one exists or create one if it doesn't
         * @param c
         * @returns {*}
         */
        getInstance: function (c) {

            if (!this._instances[c]) {
                this._instances[c] = new c;
            }

            return this._instances[c];
        }
    });

    provide(Singleton);

});

/* global modules:false */
modules.define('my-singleton', ['inherit', 'singleton'], function (provide, inherit, Singleton, MySingleton) {

    /** @class MySingleton */
    MySingleton = inherit(Singleton, /** @lends MySingleton.prototype */ {

        /**
         * @constructor
         * @private
         */
        __constructor: function () {
            this._property = null;
        },

        setProperty: function (property) {
            this._property = property;
        },

        getProperty: function () {
            return this._property;
        }

    }, /** @lends MySingleton */ {

        getInstance: function () {
            return this.__base(this);
        }

    });

    provide(MySingleton);

});

modules.require(['my-singleton'], function (mySingleton) {
    var singleA = mySingleton.getInstance();
    var singleB = mySingleton.getInstance();
    alert(singleA === singleB)
});