Too much singletons in the project - is it a bad practice?

后端 未结 4 1647
我在风中等你
我在风中等你 2020-12-19 16:46

In almost every project I create a few classes which implement Singleton pattern. For example, data manager - if there\'s some work with file system, data loader - if an app

4条回答
  •  时光取名叫无心
    2020-12-19 17:15

    Interesting article on singleton being an anti-pattern, although I don't quite agree. I've never used the singleton as a stand alone solution, I've always coupled it with the factory pattern, which I think dissuades the argument of state and encapsulation.

    A good example of a singleton/factory solution is a database class. You may have several databases, each of which require their own connection, yet you don't want every call to instantiate and create a new connection. You want to recycle shared connections to avoid the 'too many connections' landmine.

    Something along the lines of:

    /**
     * Database manager for handling database related stuff
     * Does use Zend_Db and Zend_Config
     */
    class Database_Manager
    {
        protected static $dbos = array(); // Protected scope enforces encapsulation
    
        public static function getDbo($name)
        {
            // Init
            $hash = md5($name);
    
            // Attempt to use singleton     
            if (array_key_exists($hash, self::$dbos)) {
                return self::$dbos[$hash];
            }
    
            // Your db connection settings are set here either via
            // switch/case based on name, or loaded from a config file (yaml, xml, etc)
            $dbConnectionParams = array('your', 'connection', 'settings');
    
            $config = new Zend_Config($dbConnectionParams);
    
            $dbo = Zend_Db::factory($config->database);
    
            // Adding to singleton so can be referenced in future calls
            self::$dbos[$hash] = $dbo;
    
            return $dbo;
    }
    

    In this example, the factory ensures encapsulation, while the singleton recycles already instantiated database objects.

    At the end of the day it's up to you and what you want to support down the road.

提交回复
热议问题