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);
    

      

  • 相关阅读:
    学会用google吧,,,
    HDU 2120 Ice_cream's world I
    ZOJ 3471 Most Powerful (状压DP)
    POJ 2192 Zipper
    我的闪存汇总
    Python For Delphi更好地协同(续)
    Python For Delphi更好地协同
    官方的正则表达式组件 RegularExpressions : 基本应用(转自万一博客)
    Thread: DataSnap detect disgraceful disconnect
    window7下安装IPython
  • 原文地址:https://www.cnblogs.com/echojson/p/10789532.html
Copyright © 2011-2022 走看看