The singleton pattern is the simplest of design patterns, so it seems a logical place to start, it allows us to make sure that the instantiation of a class results in only one object.
This is useful when you only ever want one instance of an object, take for example a printer port (LPT not USB and yes I am that old), older computers came out with 1 LPT port on the motherboard.
So lets say you are writing a program that makes use of the port, and assuming that you can only ever access the port with one connection, you could use a singleton to ensure that the communication to the port is only ever handled through one object, regardless of how you instantiate it and what your names are.
Below is an example (in PHP 5) of a singleton pattern, this was taken from www.php.net.
-
class Example
-
{
-
// Hold an instance of the class
-
private static $instance;
-
-
// A private constructor; prevents direct creation of object
-
private function __construct()
-
{
-
echo 'I am constructed';
-
}
-
-
// The singleton method
-
{
-
$c = __CLASS__;
-
self::$instance = new $c;
-
}
-
-
return self::$instance;
-
}
-
-
// Example method
-
public function bark()
-
{
-
echo 'Woof!';
-
}
-
-
// Prevent users to clone the instance
-
public function __clone()
-
{
-
}
-
-
}
So as you can see from the 'singleton()' function, it first checks to see if an instance of itself exists, if there is no instance of itself, then it instantiates itself and returns the object. If it does find that an object already exists it merely returns that object.
Calling the singleton pattern from code would be done as follows, this is also from the php.net site;
-
// This would fail because the constructor is private
-
$test = new Example;
-
-
// This will always retrieve a single instance of the class
-
$test = Example::singleton();
-
$test->bark();
-
-
// This will issue an E_USER_ERROR.
-
$test_clone = clone $test;
So Example::singleton(); will always return a single instance of the class.
The most common use of singleton patterns seem to be for database classes, though it can be used whenever a resource (such as a database or port) may only be used once, or when many identical instances in different parts of the website represent the same thing (no matter where you reference a database object it still represents the database class).
Posted under Design Patterns
This post was written by Shaun on October 28, 2009
