Singleton Pattern

The pattern allows:

  • control over concrete class instantiating so that the only instance could be obtained.

Singleton Pattern


PHP Example

For Registry we need the only instance of the corresponding object, globally accessible. So, Registry is often implemented as a Singleton. By the way, the Registry can be also used to keep instances of objects. This way we may be sure that the same instance consumed every time we request the object from the Registry.


<?php
/*
 * @category Design Pattern Tutorial
 * @package Singleton Sample
 * @author Dmitry Sheiko <me@dsheiko.com>
 * @link http://dsheiko.com
 */

class Registry
{
    private static $_instance = null;
    private $_data = array();

    public static function getInstance()
    {
        if (self::$_instance) {
            return self::$_instance;
        }
        return (self::$_instance = new self());
    }

    public function  __set($name,  $value)
    {
        $this->_data[$name] = $value;
    }
    public function  __get($name)
    {
        return (isset ($this->_data[$name]) ? $this->_data[$name] : null);
    }

}
/**
 * Usage
 */
Registry::getInstance()->aVar = 'aValue';
var_dump(Registry::getInstance()->aVar);

JS/ES5 Example

/*
 * @category Design Pattern Tutorial
 * @package Singleton Sample
 * @author Dmitry Sheiko <me@dsheiko.com>
 * @link http://dsheiko.com
 */
(function() {

var Registry = (function(){
    var data = {};
    return {
        set : function(name, value) {
            data[name] = value;
        },
        get : function(name) {
            return data[name];
        }
    }
})();

/*
 * Usage
 */
Registry.set('aVar', 'aValue');
alert(Registry.get('aVar'));

}());