oop – Singleton pattern

Question:

Show me what the Singleton is for ?

class Singleton {

    protected static $instance;  // object instance

    /**
     * Защищаем от создания через new Singleton
     *
     * @return Singleton
     */
    private function __construct() { /* ... */ }

    /**
     * Защищаем от создания через клонирование
     *
     * @return Singleton
     */
    private function __clone() { /* ... */ }

    /**
     * Защищаем от создания через unserialize
     *
     * @return Singleton
     */
    private function __wakeup() { /* ... */ }

    /**
     * Возвращает единственный экземпляр класса
     *
     * @return Singleton
     */
    public static function getInstance() {
        if ( is_null(self::$instance) ) {
            self::$instance = new Singleton;
        }
        return self::$instance;
    }

    public function doAction() { /* ... */ }

}

//usage
Singleton::getInstance()->doAction();

Why write like this? If you can write like this:

class Singleton {
    public static function doAction() { /* ... */ }
}

Singleton::doAction();

Not easier, no? %)

Just do not need to give links to Wikipedia, etc.


Thanks to all! @knes , @ikoolik, and @ Nord001gave you 25 points for trying.

Answer:

Singleton is needed to know for sure that we have created ONE object of this class. A classic example is a database connection.

If a bunch of scripts inside one file fiddles with the database in different functions, you have to set up a global connection variable and constantly check whether it is alive, in case the first connection to the database is in progress.

Singleton itself creates a connection if it has not been established yet, or simply returns a ready-made link. You only need to call it, no longer worrying about anything: once again, the base will not be disturbed.

Your second example is bad in that you can create a bunch of objects of this class that will not know what is happening with the rest.

Scroll to Top