zoukankan      html  css  js  c++  java
  • Yii2 设计模式——工厂方法模式

    工厂方法模式

    模式定义

    工厂方法模式(Factory Method Pattern)定义了一个创建对象的接口,但由子类决定要实例化的类是哪一个。工厂方法让类吧实例化推迟到子类。

    什么意思?说起来有这么几个要点:

    • 对象不是直接new产生,而是交给一个类方法去完成。比如loadTableSchema()方法
    • 这个方法是抽象的,且必须被子类所实现
    • 这个提供实例的抽象方法需要参与到其他逻辑中,去完成另一项功能。比如loadTableSchema()方法出现在getTableSchema()方法中,参与实现获取数据表元数据的功能
    认识工厂方法模式

    所有的工厂模式都是用来封装对象的创建。工厂方法模式通过让子类来决定创建的对象是什么,从而达到将对象创建的过程封装的目的。

    应用举例

    yiidbSchema抽象类中:

    //获取数据表元数据
    public function getTableSchema($name, $refresh = false)
    {
        if (array_key_exists($name, $this->_tables) && !$refresh) {
            return $this->_tables[$name];
        }
    
        $db = $this->db;
        $realName = $this->getRawTableName($name);
    
        if ($db->enableSchemaCache && !in_array($name, $db->schemaCacheExclude, true)) {
            /* @var $cache Cache */
            $cache = is_string($db->schemaCache) ? Yii::$app->get($db->schemaCache, false) : $db->schemaCache;
            if ($cache instanceof Cache) {
                $key = $this->getCacheKey($name);
                if ($refresh || ($table = $cache->get($key)) === false) {
                    //通过工厂方法loadTableSchema()去获取TableSchema实例
                    $this->_tables[$name] = $table = $this->loadTableSchema($realName);
                    if ($table !== null) {
                        $cache->set($key, $table, $db->schemaCacheDuration, new TagDependency([
                            'tags' => $this->getCacheTag(),
                        ]));
                    }
                } else {
                    $this->_tables[$name] = $table;
                }
    
                return $this->_tables[$name];
            }
        }
        //通过工厂方法loadTableSchema()去获取TableSchema实例
        return $this->_tables[$name] = $this->loadTableSchema($realName);
    }
    
    //获取TableSchema实例,让子类去实现
    abstract protected function loadTableSchema($name);
    

      

  • 相关阅读:
    Vsftp的PASV mode(被动模式传送)和Port模式及 Linux下VsFTP配置全方案
    vsftpd:500 OOPS: vsftpd: refusing to run with writable root inside chroot ()错误的解决方法
    CentOS7.2部署FTP
    Apache与Nginx的优缺点比较
    MySQL存储引擎--MyISAM与InnoDB区别
    CentOS 7下搭建配置SVN服务器
    Remi 安装源
    tmpx75 I2C 温度传感器驱动程序添加
    QT 5.7.0 交叉编译记录
    am335x SGX 移植
  • 原文地址:https://www.cnblogs.com/echojson/p/10789532.html
Copyright © 2011-2022 走看看