php设计模式 四 (原型模式 迭代器模式)

来源:互联网 发布:知识分子的鸦片 知乎 编辑:程序博客网 时间:2024/06/05 19:19

原型模式

与工厂模式类似,用于创建对象,不同的是原型模式先创建好一个原型对象,通过clone原型对象来创建新的对象,如此就避免了类创建时的重复的初始化操作,一般用于大对象的创建,免去了每次new的重复消耗,而只是内存拷贝。
它主要面对的问题是:“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是他们却拥有比较稳定一致的接口。

示例代码:

/* 原型模式 */class BigClass {function init() {;}function exec($tpye) {echo "prototype$tpye<br>";}}/** * 原型用户大对象的创建 节约资源 */$prototype = new BigClass();$prototype->init();$bigClass1 = clone $prototype;$bigClass2 = clone $prototype;$bigClass1->exec(1);$bigClass2->exec(2);


迭代器模式

在不需要了解内部实现的情况下,遍历一个聚合对象的内部元素。相比传统编程模式,迭代器模式可以隐藏遍历元素所需操作

迭代器示例UserIterator.php

<?phpnamespace Components\Iterator;use Components\Register;use Components\Factory;class UserIterator implements \Iterator {protected $ids;protected $data = array();protected $index;function __construct() {$db = Register::get('slave');$result = $db->query('select id from users');$this->ids = $result->fetch_all(MYSQL_ASSOC);}//1function rewind(){$this->index = 0;}//2function valid(){return $this->index < count($this->ids);}//3function current() {return Factory::getUser($this->ids[$this->index]['id']);}//4function next() {++$this->index;}//5function key() {return $this->index;}}

使用:
/* 迭代器模式 */$users = new UserIterator();foreach ($users as $user) {var_dump($user);}


0 0
原创粉丝点击