工厂模式和单利模式实现实例化工具

   protected static $instance=[];
    protected $namespace = 'app\common\model\\';
    /**
     * @desc: 产生对象的工厂类
     * @user: callmelx
     * @date: 2019/8/27 13:36
     */
    protected function factory($model,$namespace=''){
        if(!$namespace){
            $namespace = $this->namespace;
        }
        $className = $namespace.$model;
        $obj = self::$instance[$model]??"";
        if (!($obj  instanceof $className)) {
            self::$instance[$model] = new $className();
        }
        return self::$instance[$model];
    }

 下面是基于tp5.1容器实现的:

容器在绑定以后自动是单利的模式:

protected function create($model){
        $exist = isset(app()->$model);
        if(!$exist){
            $className = $this->namespace.$model;
            $obj = app()->$model = new $className;
        }else{
            $obj = app()->$model;
        }
        return $obj;
    }

 

posted @ 2019-08-28 13:48  callmelx  阅读(195)  评论(0编辑  收藏  举报