php 设计模式之单例模式

单例模式的关键点

1、//私有构造函数,防止直接new 创建实例

2、//设置静态成员变量 作保存实例

3、//公有访问实例的静态方法

4、//防止克隆对象的方法

上代码:

//单例模式

class danli

{

    //静态成员变量 作保存实例

    private static $_instance;

    private $config;

    //私有构造函数,防止直接new 创建对象

    private function __construct($config)

    {

        $this->config = $config;

        echo 'ok';

    }

    //公有访问实例的静态方法

    public static function getInstance($config)

    {

        if(!(self::$_instance instanceof self))

        {

            self::$_instance = new self($config);

        }

        return self::$_instance;

    }

    //防止克隆对象

    public function __clone()

    {

        trigger_error('Clone is not allow' ,E_USER_ERROR);

    }

    //测试方法

    public function test()

    {

        echo '调用成功';

        echo '<br/>';

        echo $this->config;

    }

}

//测试

$test = danli::getInstance('设置配置');

$test->test();

猜你喜欢

转载自www.cnblogs.com/yangshjing/p/9171518.html