Added singleton pattern to the Design-Patterns page

This commit is contained in:
Corey McMahon
2013-01-09 17:59:24 +11:00
parent 1eb4f18d46
commit 7850ebd5e4

View File

@@ -62,6 +62,50 @@ yourself a lot of trouble down the road by using factories.
* [Factory pattern on Wikipedia](https://en.wikipedia.org/wiki/Factory_pattern)
## Singleton
When designing web applications, it often makes sense conceptually and architecturally to allow access to one and
only one instance of a particular class. The singleton pattern enables us to do this.
{% highlight php %}
<?php
class Singleton
{
static $instance;
private function __construct()
{
}
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
echo $instance1 === $instance2; // outputs 1
{% endhighlight %}
The code above implements the singleton pattern using a statically scoped variable and the `getInstance()` method.
Note that the constructor is declared as private to prevent instantiation outside of the class via `new` keyword.
The singleton pattern is useful when we need to make sure we only have a single instance of a class for the entire
request lifecycle in a web application. This typically occurs when we have global objects (such as a Configuration
class) or a shared resource (such as an event queue).
You should be wary when using the singleton pattern, as by its very nature it introduces global state into your
application, reducing testability. In most cases, dependency injection can (and should) be used in place of
singleton objects.
* [Singleton pattern on Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern)
## Front Controller
The front controller pattern is where you have a single entrance point for you web application (e.g. index.php) that