工厂方法模式

模式定义

工厂方法模式(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);

  

最新文章

  1. SpringMVC上传文件的三种方式
  2. RabbitMQ Step by step(一) 安装
  3. HTML4.01和XHTML1.0和XHTML1.1的一些区别
  4. Hession矩阵与牛顿迭代法
  5. js方法和prototype
  6. 自由软件VS开源软件
  7. Virtualbox虚拟机设置不完全笔记
  8. CGAL 介绍
  9. 开发设计模式(四) 代理模式(Proxy Pattern)
  10. Java 大数类
  11. 【Java编程】Eclipse快捷键
  12. Netty从入门到精通到放弃
  13. vim设置Tab键和显示行号
  14. Python文学家为Python写的一首词?(附中英文版)
  15. ionic2/3注册安卓返回
  16. [LeetCode&Python] Problem 541. Reverse String II
  17. CSS3 定位| Position研究
  18. 不借助autolt实现下载文件到指定目录
  19. IAR EWAR 内联汇编 Error[Og010], Error [Og005], Error [Og006]
  20. 算法笔记--树的直径 && 树形dp && 虚树 && 树分治 && 树上差分 && 树链剖分

热门文章

  1. dom编程艺术笔记1--第二章
  2. Educational Codeforces Round 63 (Rated for Div. 2) D. Beautiful Array (简单DP)
  3. bootstrap-fileinput多图片上传
  4. elasticsearch(1) 安装和使用
  5. CSS效果:跑马灯按钮
  6. 解决 error: Your local changes to the following files would be overwritten by merge:XXXX
  7. C语言进阶1-#define和const
  8. Filter 中空指针错误
  9. ngix请求转发
  10. DG_Check检测