- Intent
- enforce the existance of a single object of a specified type
- Motivation
- Application needs one, and only one, instance of an object. Additionally, lazy initialization and global access are necessary.
- Implementation
-
- use the memoize pattern to implement a singleton
- Examples
- with functions
function &get_instance() { static $instance; if(empty($instance)) { $instance = new SingletonClass(); } return $instance; } - with objects
class Singleton { private static $instance = null; private static function __construct() { } public function get_instance() { if(empty(self::$instance) { self::$instance = new Singleton(); } return self::$instance; } } - Complications
- The function based version implements the code equivalent of security by obscurity. It doesn't really enforce a single instance of a class, but a revised version can be used to abstract out singleton creation