Mark’s Site

Pensieve for coding and golf :-)

Singleton Pattern

By admin • May 17th, 2008 • Category: 2.3.1. Creational Patterns

The singleton design pattern is used to ensure a class has only one instance, and that global access to that instance is available. In other words, it restricts instantiation of a class to one object.

When I first read this concept I just didn’t get it (I’m a bit slow). But it’s really pretty simple. You just have to know your terms. A class defines the structure of an object, and to use that class, we instantiate an object of the class. So take the following php:

<?php
//create an instance of the Product class
$product_object = new Product();
//print the product's name
echo $product_object->product_name;

//create another instance of the Product class
$product_object2 = new Product();
//do other stuff
//...
?>

In this example, ‘Product’ is the class and ‘$product_object’ and ‘$product_object2′ are instances of the Product class.

We use the singleton pattern by creating a class with a function that creates a new instance of the class only if one does not exist. If an instance does already exist, it simply returns a reference to that object. This ensures you only have one instance at any one time, hence singleton.

So in the above php for example, if our Product class used the singleton pattern, ‘$product_object’ and ‘$product_object2′ would in fact be referring to the same instance of the Product class.

Why is this useful?

Well firstly I imagine this would use less system resources. If it’s only ever referencing one instance, memory usage would be kept to a minimum, so one could argue a performance advantage.

Secondly I could see this pattern useful in complicated systems where you need a be referencing a single object at any given time, perhaps a User object, to coordinate actions in different parts of the system, or sub systems. A user object is often referenced in many different parts of the system, so always referencing the one instance would be beneficial.

Real world example

Here is some example code from the PHP manual on how to create a class that uses the singleton pattern:

<?php
class Singleton{
	// $instance holds a single instance of the object
	private static $instance;
	// private constructor
	private function __construct(){}
	// the getInstance() method returns a single instance of the object
	public static function getInstance(){
		if(!isset(self::$instance)){
			$object= __CLASS__;
			self::$instance=new $object;
		}
		return self::$instance;
	}
	public function displayMessage(){
		echo 'I am a Singleton';
	}
}
$singleton=Singleton::getInstance();//return a single instance of the object
$singleton->displayMessage();// display message
?>

And here is another useful example I found that you can use that is more animated …run this and you’ll see the singleton output inform you that only one instance exists at a time :-)

<?php
echo '1:';
$user_1 = CurrentUser::singleton();

echo '2:';
$user_1->counter();

echo '3:';
$user_2 = CurrentUser::singleton();

/* Singleton Class: CurrentUser */
class CurrentUser {
    // Hold an instance of the class
    private static $instance;
    private $counter = 0;

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

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

    public function counter() {
        echo 'CurrentUser -> counter = ' . $this->counter;
        ++$this->counter;
    }
}
?>

(original source)

admin is
Email this author | All posts by admin

Leave a Reply