单例模式的实现

Original 2019-05-21 11:06:51 163
abstract:<?php //单例模式 class Test { } $test1 = new Test(); $test2 = new Test(); echo ($test1 instanceof Test)?'是':'否'; echo '<b
<?php
//单例模式
class Test
{

}
$test1 = new Test();
$test2 = new Test();

echo ($test1 instanceof Test)?'是':'否';
echo '<br>';
echo ($test2 instanceof Test)?'是':'否';
echo '<br>';
echo ($test1 === $test2)?'是':'否';
echo '<br>';
var_dump($test1,$test2);
class Tag
{
    //私有化构造方法,防止外部实例化类
    private function __construct(){ }
    //私有化克隆方法,防止克隆类
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }
    //创建一个类的内部静态方法,保存类的唯一实例
    protected static $instance = null;
    //创建一个外部接口,创建并返回类的唯一实例
    public static function getInstance()
    {
        if (is_null(self::$instance)){
            self::$instance = new static();
        }
        return self::$instance;
    }
}

$test3 = Tag::getInstance();
$test4 = Tag::getInstance();

echo ($test3 instanceof Tag)?'是':'否';
echo '<br>';
echo ($test4 instanceof Tag)?'是':'否';
echo '<br>';
echo ($test3 === $test4)?'是':'否';
echo '<br>';
var_dump($test3,$test4);


Correcting teacher:查无此人Correction time:2019-05-22 09:15:10
Teacher's summary:完成的不错,php有很多设计模式,可以多了解。继续加油。

Release Notes

Popular Entries