php设计模式之工厂模式

72
发布时间:2024-07-04 09:06:07

工厂模式,工厂方法或者类生成对象,而不是在代码中直接new。
使用工厂模式,可以避免当改变某个类的名字或者方法之后,在调用这个类的所有的代码中都修改它的名字或者参数。

Test1.php
<?php
class Test1{
    static function test(){
        echo __FILE__;
    }
}

Factory.php
<?php
class Factory{
    /*
     * 如果某个类在很多的文件中都new ClassName(),那么万一这个类的名字
     * 发生变更或者参数发生变化,如果不使用工厂模式,就需要修改每一个PHP
     * 代码,使用了工厂模式之后,只需要修改工厂类或者方法就可以了。
     */
    static function createDatabase(){
        $test = new Test1();
        return $test;
    }
}

Test.php
<?php
spl_autoload_register('autoload1');

$test = Factory::createDatabase();
$test->test();
function autoload1($class){
    $dir  = __DIR__;
    $requireFile = $dir."\\".$class.".php";
    require $requireFile;
}



Test1.php
<?php
class Test1{
    protected static  $tt;
    private function __construct(){}
    static function getInstance(){
        if(self::$tt){
            echo "对象已经创建<br>";
            return self::$tt;
        }else {
            self::$tt = new Test1();
            echo "创建对象<br>";
            return self::$tt;
        }
    }
     function echoHello(){
        echo "Hello<br>";
    }
}
Test.php
<?php
spl_autoload_register('autoload1');

$test = Test1::getInstance();
$test->echoHello();
$test = Test1::getInstance();
$test->echoHello();
$test = Test1::getInstance();
$test->echoHello();
$test = Test1::getInstance();
$test->echoHello();
function autoload1($class){
    $dir  = __DIR__;
    $requireFile = $dir."\\".$class.".php";
    require $requireFile;
}

本文被 PHP编程 专题收录