If you use this, only do so for logging. This pattern is widely described as an anti-pattern, don’t tell me I did not warn you: Patterns I Hate #1: Singleton, Singleton (…) you’re bringing me down. Still, I do like this pattern because if its simplicity, and Dependency Injection or the Factory pattern is for small projects sometimes just overkill.
This pattern ensures there is only one instance of a class active.
This is useful for logging, where you only need one logging instance.
The implementation itself is quite simple:
php (for C# see here: github):
class Singleton { //overwrite those two methods to "disable" them private function __clone() {} private function __construct() {} //our saved instances protected static $instances = array(); /** * @return static */ final public static function getInstance() { $classname = get_called_class(); if (!isset(static::$instances[$classname])) { static::$instances[$classname] = new static(); } return static::$instances[$classname]; } }
To use this pattern you simply inherit from the singleton class, and then call MyOneAndOnly::getInstance()
(php) or MyOneAndOnly.Instance.HelloWorld
(C#)
class MyOneAndOnly extends Singleton { public function helloWorld() { return "hello"; } } echo MyOneAndOnly::getInstance()->helloWorld(); //prints "hello"
Only use this pattern if your application does not depend on the data of the Singleton
; you only pass data to the object, but never retrieve any. This scenario is true for a Logger, or for a Stopwatch to test the performance of your application. For any other scenario fo not use this, as it makes your code harder to understand and to test