Home >Backend Development >PHP Tutorial >PHP Design Patterns - Singleton Pattern_PHP Tutorial
The singleton pattern, also called singleton, is the simplest of the 23 design patterns. You can know its core idea from its name. The singleton pattern means that there is only one such object in the system, and there is only one object. , in Java or C#, there are generally two types of singleton modes, namely lazy mode and hungry mode. However, the lazy mode is commonly used in PHP. Since PHP is single-threaded, there is no double verification in the lazy mode.
Lazy man style specific code:
<!--?php /** * Created by PhpStorm. * User: LYL * Date: 2015/4/21 * Time: 21:25 */ /**懒汉式 * Class Singleton */ class Singleton { //创建静态对象变量 private static $instance=null; public $age; //构造函数私有化,防止外部调用 private function __construct() { } //克隆函数私有化,防止外部克隆对象 private function __clone() { } //实例化对象变量方法,供外部调用 public static function getInstance() { if(empty(self::$instance)) { self::$instance=new Singleton(); } return self::$instance; } } </pre--> 测试代码:
$single1=Singleton::getInstance(); $single1->age=22; $single2=Singleton::getInstance(); $single2->age=24; echo 变量1的age:{$single1->age} ; echo 变量2的age:{$single2->age} ;
Through the above code, I can organize the three steps of writing the singleton pattern:
1. Create a class static variable
2. Privateize the constructor and clone function to prevent external calls
3. Provide a static method that can be called externally and instantiate the static variable created in the first step
Obviously, the applicable scenario of the singleton mode is when only one object in the system is needed, for example, Spring's Bean factory in Java, database connection in PHP, etc. As long as there is such a need, singleton Example mode.
PHP object-oriented design patterns