Home  >  Article  >  Backend Development  >  The difference between php factory mode and singleton mode

The difference between php factory mode and singleton mode

藏色散人
藏色散人Original
2019-10-09 10:27:312779browse

The difference between php factory mode and singleton mode

The difference between php factory mode and singleton mode

Singleton mode: prevent repeated instantiation and avoid a large number of The new operation reduces the consumption of system and memory resources, so that there is only one instance object

header("Content-type: text/html; charset=utf-8");   //定义字符编码,防止乱码
/**
 * 单利类
 */
class Single
{
    private static $_instance;  //保存实例的对象
 
 
    private function __construct()  //定义构造方法
    {
 
    }
 
    private function __clone()  //定义一个空方法防止被外部克隆
    {  
 
    }
 
 
    public static function getInstance()    //定义一个获取实例对象的方法
    {
        if (!(self::$_instance  instanceof Single)) {
            self::$_instance = new self();
        }
        return self::$_instance;        //返回实例对象
    }
 
    /**
     * 测试方法
     */
    public function test()
    {
        echo "单利模式";
    }
 
}
 
 
$run=Single::getInstance();
$run->test();

Factory mode: a mode that uses factory methods to replace the new operation. If you need to change the instantiated class name, Just modify it in the factory method, there is no need to look for specific instantiation places in the code one by one

header("content-type:text/html;charset=utf-8"); //定义字符编码,防止乱码
/**
 * 测试类一
  */
class demo1
{
    //定义一个test1方法
    public function test1()
    {
        echo '这是demo1类的test1方法'.PHP_EOL;
    }
}
/**
 * 测试类二
  */
class demo2
{
    //定义一个test2方法
    public function test2()
    {
        echo '这是demo2类的test2方法'.PHP_EOL;
    }
}
/**
 * 工厂类
 */
class Factoty
{
    // 根据传参类名,创建对应的对象
    static function createObject($className)
    {
        return new $className();
    }
}
/**
 * 通过传类名,调用工厂类里面的创建对象方法
 */
$demo = Factoty::createObject('demo1');
$demo->test1();             //输出这是demo1类的test1方法
$demo = Factoty::createObject('demo2');
$demo->test2();            //输出这是demo2类的test2方法

For more PHP knowledge, please visit PHP Chinese website!

The above is the detailed content of The difference between php factory mode and singleton mode. For more information, please follow other related articles on the PHP Chinese website!

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