As a common design mode, Singleton mode is widely used. So how to design a singleton is the best?
We usually write this way, and most examples that can be found on the Internet are as follows:
Copy codeThe Code is as follows:
Class
{
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
{
Protected static $ _ instance = null;
}
$ A = A: getInstance ();
$ B = B: getInstance ();
Var_dump ($ a ===$ B );
Set the _ construct Method to private to prevent this class from being instantiated by others. But the obvious problem with this writing method is that the Code cannot be reused. For example, A class inherits:
Copy codeThe Code is as follows:
Class B extends
{
Protected static $ _ instance = null;
}
$ A = A: getInstance ();
$ B = B: getInstance ();
Var_dump ($ a ===$ B );
The above code will output:
Copy codeThe Code is as follows:
Bool (true)
The problem lies in self. the reference of self is determined when the class is defined. That is to say, if A inherits B, its reference of self still points to. To solve this problem, the static binding feature is introduced in PHP 5.3. In short, the static keyword is used to access static methods or variables. Unlike self, static references are determined by the runtime. So we simply rewrite our code so that the singleton mode can be reused.
Copy codeThe 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 );
The above code output:
Copy codeThe Code is as follows:
Bool (false)
In this way, the singleton mode can be implemented simply by inheriting and re-initializing the $ _ instance variable. Note that the above method can only be used in PHP 5.3. For PHP of the previous version, write a getInstance () method for each Singleton class.
It should be noted that although the single-sample mode in PHP does not have the same thread security issues as in Java, you must be careful when using the single-instance mode for stateful classes. Classes in the singleton mode will be accompanied by the entire lifecycle of PHP running, which is also an overhead for memory.