As a common design pattern, the single case pattern is widely used. So how to design a single example is the best?
Usually we write this, and most of the examples that can be found on the Web are this:
. The code is as follows:
Class A
{
protected static $_instance = NULL;
protected function __construct ()
{
Disallow new instance
}
protected function __clone () {
Disallow clone
}
Public Function getinstance ()
{
if (self::$_instance = = null) {
Self::$_instance = new self ();
}
return self::$_instance;
}
}
Class B extends A
{
protected static $_instance = NULL;
}
$a = a::getinstance ();
$b = B::getinstance ();
Var_dump ($a = = = $b);
By setting the __construct method private, you can guarantee that the class is not instantiated by someone else. But one obvious problem with this type of writing is that code cannot be reused. For example, we inherit a in one class:
. The code is as follows:
Class B extends A
{
protected static $_instance = NULL;
}
$a = a::getinstance ();
$b = B::getinstance ();
Var_dump ($a = = = $b);
The code above will output:
. The code is as follows:
BOOL (TRUE)
The problem with self is that the reference to self is determined when the class is defined, that is, the A that inherits B, and his self reference still points to a. To solve this problem, a late static binding feature was introduced in PHP 5.3. In a nutshell, a static keyword is used to access a method or variable, and unlike self, static references are determined by the runtime. So simply rewrite our code so that the single example pattern can be reused.
. The code is as follows: Class C
{
protected static $_instance = NULL;
protected function __construct ()
{
}
protected function __clone ()
{
Disallow clone
}
Public Function getinstance ()
{
if (static::$_instance = = null) {
Static::$_instance = new Static;
}
return static::$_instance;
}
}
Class D extends C
{
protected static $_instance = NULL;
}
$c = C::getinstance ();
$d = D::getinstance ();
Var_dump ($c = = = $d);
Above code output:
. The code is as follows:
BOOL (FALSE)
This allows simple inheritance and reinitialization of $_instance variables to implement the single case pattern. Note that the above method can only be used in PHP 5.3, for previous versions of PHP, or honestly for each single case class to write a getinstance () method.
You need to be reminded that the single example mode in PHP does not have a thread-safe problem like Java, but for stateful classes, use a single case pattern carefully. Single-mode classes can be associated with the entire lifecycle of PHP running, which is also a cost for memory.