Sunday, June 7, 2009

Design Pattern Singleton

Singleton is a creational pattern which ensures a class has only one instance, and provide a global pointer to access it.
The most common example is a database connection.

The idea: the class doesn't provide a constructor, but a method to return an instance. That instance is assigned to a static properties and is instantiated only at the 1st access.

class Example
{
// Hold an instance of the class
private static $instance;

// A private constructor; prevents direct creation of object
private function __construct() { }

// The singleton method
public static function singleton()
{
if (!isset(
self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return
self::$instance;
}

// Prevent users to clone the instance
public function __clone() { trigger_error('Clone is not allowed.', E_USER_ERROR); }

}

No comments:

Post a Comment

 

PHP and tips|PHP