These are chat archives for bem/talk

5th
Aug 2014
Ilya Rogov
@ilyar
Aug 05 2014 08:43

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);

});
Alexander Savin
@apsavin
Aug 05 2014 09:58
@ilyar, why not
modules.define('my-singleton', function (provide) {
    var MySingleton = function(){};
    provide(new MySingleton());
});
Sergey Berezhnoy
@veged
Aug 05 2014 11:23
@ilyar describe more what you wanna achieve — otherwise I +1 with @apsavin ;-)
Ilya Rogov
@ilyar
Aug 05 2014 14:25
/**
* Usage singleton
* @link http://jsfiddle.net/ilyar/8A5AB/
*/
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)
});
Ilya Rogov
@ilyar
Aug 05 2014 14:46
@veged I want to hear criticism of the implementation of the Singleton pattern.
Sergey Berezhnoy
@veged
Aug 05 2014 15:46

@ilyar I can't catch the point, why you need such separate block? you can simple use approach which suggested by @apsavin or use inherit in similar manner

also, implement of getInstance method for my-singleton looks unnecessary