原型模式的核心角色定义
在原型模式的设计架构中,主要包含两个核心角色。
抽象原型(Prototype)角色负责声明一个用于克隆自身的接口;具体原型(Concrete Prototype)角色则实现该接口,提供克隆自身的具体操作逻辑。
当某个类的绝大多数属性相同,仅少数部分存在差异时,若需创建大量该类实例,每次重复实例化相同部分将产生巨大开销。若在克隆前预先建立包含相同部分的对象基础,即可有效节约资源消耗。
针对PHP语言的一种实现策略是将__construct()函数与initialize()函数分离,分别处理类的初始化过程。其中,__construct()存放作为原型的公共部分代码,而initialize()则处理每个对象特有的部分。首先建立一个未调用initialize的类实例,随后每次克隆该实例后再执行initialize操作。
Zend Framework官方手册中提及了相关概念,链接为http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html,但未深入展开。下文将对这一机制进行详细分析。
一、背景引入
在ZF2的Model层中存在一个名为albumTable的类,它充当操作数据库的助手类,内部使用了TableGateway组件。
为确保每次初始化AlbumTable时保持一致性,初始化工作被放置在根目录module.php文件的getServiceConfig()方法中。此处运用了工厂模式,并通过回调函数机制,当ServiceManager($sm)需要实例化对象时自动触发创建AlbumTable的逻辑。从代码可见,创建AlbumTable还需以相同方式创建一个AlbumTableGateway,而该类正是原型模式的应用场景。
二、代码深度解析
public function getServiceConfig()
{
return array(
'factories' => array(
'Album\Model\AlbumTable' => function($sm) {
$tableGateway = $sm->get('AlbumTableGateway');
$table = new AlbumTable($tableGateway);
return $table;
},
'AlbumTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Album());//这个就是一个不变的原型
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);//传入到TableGateWay的构造函数中去
},
),
);
}
需要注意的是,运用原型模式的并非TableGateway本身,而是ResultSet类。每当TableGateway调用select()或insert()等方法时,都会新建一个ResultSet来表示结果集。这些ResultSet中的公共部分会被克隆,而如data等独特部分则通过initialize方法进行初始化。
三、更多代码示例
为了更清晰地理解原型模式,我们暂时脱离Zend框架这个大环境,查看一个完整的独立代码示例。
该示例源自http://ralphschindler.com/2012/03/09/php-constructor-best-practices-and-the-prototype-pattern一文,标题为PHP Constructor Best Practices And The Prototype Pattern。
这篇文章关于原型模式的前半部分混杂了如何在构造函数中运用继承以提高扩展性的内容,两种模式交织可能难以理解。因此,我们直接聚焦于文末关于原型模式的代码部分。
<?php
//框架中很常见的adapter类,用来适配各种数据库,封装一些基本数据库连接操作。
//相当于上面代码中的adapter类
class DbAdapter {
public function fetchAllFromTable($table) {
return $arrayOfData;
}
}
//运用prototype pattern的类,注意construct和initialize是分开的
//相当于上面zend 代码里面的ResultSet类
class RowGateway {
public function __construct(DbAdapter $dbAdapter, $tableName) {
$this->dbAdapter = $dbAdapter;
$this->tableName = $tableName;
}
public function initialize($data) {
$this->data = $data;
}
/**
* Both methods require access to the database adapter
* to fulfill their duties
*/
public function save() {}
public function delete() {}
public function refresh() {}
}
//相当于上面代码中的TableGateway类,关于gateway可以具体去了解一下。
class UserRepository {
public function __construct(DbAdapter $dbAdapter, RowGateway $rowGatewayPrototype = null) {
$this->dbAdapter = $dbAdapter;
$this->rowGatewayPrototype = ($rowGatewayPrototype) ? new RowGateway($this->dbAdapter, 'user')
}
public function getUsers() {
$rows = array();
foreach ($this->dbAdapter->fetchAllFromTable('user') as $rowData) {
$rows[] = $row = clone $this->rowGatewayPrototype;
$row->initialize($rowData);
}
return $rows;
}
}
这几个类实际上对应上文Zend代码中的类结构。
DbAdapter对应Adapter。
RowGateway对应ResultSet。
UserRepository对应TableGateway。
具体细节请参见代码中的注释说明。
在RowGateway的getUsers方法中可以看出需要大量实例化对象,此时原型模式的应用显得尤为必要。
以下是使用该类的具体代码片段。
class ReadWriteRowGateway extends RowGateway {
public function __construct(DbAdapter $readDbAdapter, DbAdapter $writeDbAdapter, $tableName) {
$this->readDbAdapter = $readDbAdapter;
parent::__construct($writeDbAdapter, $tableName);
}
public function refresh() {
// utilize $this->readDbAdapter instead of $this->dbAdapter in RowGateway base implementation
}
}
// usage:
$userRepository = new UserRepository(
$dbAdapter,
new ReadWriteRowGateway($readDbAdapter, $writeDbAdapter, 'user')
);
$users = $userRepository->getUsers();
$user = $users[0]; // instance of ReadWriteRowGateway with a specific row of data from the db
以上内容是小编给大家介绍的php示例详解Constructor Prototype Pattern 原型模式,希望大家喜欢。