设计模式-单例模式

1.什么是单例模式

1.一个类只有一个实例对象

2.整个系统都使用这个实例

2.例子

class test{
    static private $_instance;

    public static function getInstance()
    {
        if(empty(self::$_instance))
        {
            self::$_instance =new test();
        }

        return self::$_instance;
    }
    public function my()
    {
        echo 'mymy';
    }
}
//$obj1,$obj2,$obj3相等
$obj1=test::getInstance();
$obj2=test::getInstance();
$obj3=test::getInstance();

//输出mymy
echo $obj3->my();

单例可以减少创建对象的消耗,减少系统开支。

posted @ 2016-12-13 17:32  layfork  阅读(127)  评论(0编辑  收藏  举报