Statement: This series of blog reference "Big Talk design mode", author Geoscience.
Singleton mode, also known as the single State, is the simplest of 23 design patterns, from his name can know his core ideas, single-case mode is only one such object in the system, the object only one, in Java or C #, the singleton pattern generally has two kinds, namely the lazy type, the A hungry man type, But in PHP commonly used is lazy-type, because PHP is single-threaded, lazy-type also does not exist double authentication.
Lazy Type Specific code:
Test code:
$single 1=singleton::getinstance (); $single 1->age=22; $single 2=singleton::getinstance (); $single 2->age=24; echo "age:{of variable 1 $single 1->age}
age:{of "; echo" Variable 2 $single 2->age}
";
As we can see, the variable $single1, the age of $single 2 is 24, the variable $single1, $single 2 is a variable, and the class Singleton is a singleton.
With the above code, I can organize three steps to write a singleton pattern:
1. Create a class static variable
2. Privatization of constructors and cloning functions to prevent external calls
3. Provide a static method that can be called externally, instantiating the static variable created in the first step
It is obvious that the application scenario of the singleton pattern is that the object in the system needs only one, for example, the Spring Bean factory in Java, the database connection in PHP, and so on, as long as there is such a requirement, the first singleton mode.
PHP Object-oriented design pattern