php设计模式 - 单例模式

场景:有一个工具类,要频繁使用这个工具类。

通常是这么写的:

class Data{

    static public function getTool(){
        $file = 'tool.class.php';
        if(file_exists($file)){
            include $file;
            $tool = new Tool();
            return $tool;
        }
        else{
            echo $file . " is not exists!!";
        }
    }
}

Data :: getTool();

每次获取Tool类都要new一次,还要include一次。增加内存开销。

class Data{
    static private $instance;
    static public function getTool(){
        $file = "tool.class.php";
        if(isset(self :: $instance)){
            if(file_exists($file)){
                include $file;
                self :: $instance = new Tool();
            }
            else{
                echo $file . " is not exists!!";
            }
        }
        return self :: $instance;
    }
}

Data :: getTool();

单例模式:限定特定的对象(Tool)只需要被创建一次。

  1. 数据库或者redis等公用类。

  2. 单例模式可以减少类的实例化。



你可能感兴趣的:(php设计模式 - 单例模式)