Home >Backend Development >PHP Tutorial >PHP Design Patterns - Singleton Pattern_PHP Tutorial

PHP Design Patterns - Singleton Pattern_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 09:56:27953browse

PHP Design Pattern - Singleton Pattern

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}
;

We can see that the age of variables $single1 and $single2 are both 24, indicating that variables $single1 and $single2 are variables and the class Singleton is a singleton.

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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/987984.htmlTechArticlePHP Design Pattern - Singleton Mode Singleton mode, also called monomorphism, is the simplest of the 23 design patterns A kind of model. You can know its core idea from its name. The singleton mode is in the system...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn