Yii2 设计模式——工厂方法模式

工厂方法模式

模式定义

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

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

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

 

认识工厂方法模式

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

 

应用举例

yii\db\Schema抽象类中:

//获取数据表元数据
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);

  

posted on 2019-04-29 11:43  追风的浪子  阅读(301)  评论(0编辑  收藏  举报

导航