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);
最新文章
- SpringMVC上传文件的三种方式
- RabbitMQ Step by step(一) 安装
- HTML4.01和XHTML1.0和XHTML1.1的一些区别
- Hession矩阵与牛顿迭代法
- js方法和prototype
- 自由软件VS开源软件
- Virtualbox虚拟机设置不完全笔记
- CGAL 介绍
- 开发设计模式(四) 代理模式(Proxy Pattern)
- Java 大数类
- 【Java编程】Eclipse快捷键
- Netty从入门到精通到放弃
- vim设置Tab键和显示行号
- Python文学家为Python写的一首词?(附中英文版)
- ionic2/3注册安卓返回
- [LeetCode&;Python] Problem 541. Reverse String II
- CSS3 定位| Position研究
- 不借助autolt实现下载文件到指定目录
- IAR EWAR 内联汇编 Error[Og010], Error [Og005], Error [Og006]
- 算法笔记--树的直径 &;&; 树形dp &;&; 虚树 &;&; 树分治 &;&; 树上差分 &;&; 树链剖分
热门文章
- dom编程艺术笔记1--第二章
- Educational Codeforces Round 63 (Rated for Div. 2) D. Beautiful Array (简单DP)
- bootstrap-fileinput多图片上传
- elasticsearch(1) 安装和使用
- CSS效果:跑马灯按钮
- 解决 error: Your local changes to the following files would be overwritten by merge:XXXX
- C语言进阶1-#define和const
- Filter 中空指针错误
- ngix请求转发
- DG_Check检测