PHP design mode-Singleton mode statement: This series of blog reference material "big talk Design Mode", author Cheng Jie.
The Singleton mode is also called the single-state mode. it is the simplest of the 23 design modes. his core idea can be known from his name, the Singleton mode is that there is only one such object in the system, and there is only one object. in Java or C #, Singleton mode generally has two types: lazy and hungry, however, in PHP, the lazy style is commonly used. because PHP is single-threaded, there is no dual verification for lazy style.
Lazy code:
Test code:
$ Single1 = Singleton: getInstance (); $ single1-> age = 22; $ single2 = Singleton: getInstance (); $ single2-> age = 24; echo "age of variable 1: {$ single1-> age}
"; Echo" age of variable 2: {$ single2-> age}
";
We can see that the age of the variable $ single1 and $ single2 is 24, indicating that the variable $ single1, $ single2 is a variable, and the Singleton class is Singleton.
With the above code, I can organize three steps to write the Singleton mode:
1. create a static variable
2. private constructor and clone function to prevent external calls
3. provide a static method that can be called externally to instantiate the static variable created in the first step.
Obviously, the single-instance mode is applicable when only one object is needed in the system, such as the Bean factory of Spring in Java and the database connection in PHP, as long as this requirement is met, the singleton mode is used first.
PHP object-oriented design model