php迭代器模式
来源:互联网 发布:国家质检总局网络培训 编辑:程序博客网 时间:2024/06/04 20:11
1 模式介绍
提供一种方法顺序访问一个聚合对象中各个元素, 而又无须暴露该对象的内部表示。
2 模式中的角色
2.1 抽象容器:一般是一个接口,提供一个iterator()方法,例如java中的Collection接口,List接口,Set接口等。
2.2 具体容器:就是抽象容器的具体实现类,比如List接口的有序列表实现ArrayList,List接口的链表实现LinkList,Set接口的哈希列表的实现HashSet等。
2.3 抽象迭代器:定义遍历元素所需要的方法,一般来说会有这么三个方法:取得第一个元素的方法first(),取得下一个元素的方法next(),判断是否遍历结束的方法isDone()(或者叫hasNext()),移出当前对象的方法remove(),
2.4 迭代器实现:实现迭代器接口中定义的方法,完成集合的迭代。
3 模式结构
4 php源码
<?php/** * 迭代器模式 * copyright (c) http://blog.csdn.net/CleverCode *///我的迭代器标准interface MyIterator{/*{{{*/ //首个 public function first(); //下一个 public function next(); //是否结束 public function isDone(); //当前元素 public function currentItem(); //当前指针 public function currentIdx();}/*}}}*///抽象的容器abstract class Aggregate{/*{{{*/ abstract public function createIterator();}/*}}}*///具体的容器class MyAggregate extends Aggregate{/*{{{*/ public $items = array(); //容器的迭代器 public function createIterator() { return new MineIterator($this); } public function getItem($idx) { return isset($this->items[$idx]) ? $this->items[$idx] : null; } public function setItem($idx,$val) { $this->items[$idx] = $val; } public function getCount() { return count($this->items); }}/*}}}*///我具体的迭代器class MineIterator implements MyIterator{/*{{{*/ //容器【聚集对象】 private $aggregate; private $current = 0; public function __construct(MyAggregate $aggregate) { $this->aggregate = $aggregate; } //首个 public function first() { return $this->aggregate->getItem(0); } //下一个 public function next() { $ret = null; $this->current++; if($this->current < $this->aggregate->getCount()) { $ret = $this->aggregate->getItem($this->current); } return $ret; } //是否结束 public function isDone() { return $this->current >= $this->aggregate->getCount() ? true : false; } //当前元素 public function currentItem() { return $this->aggregate->getItem($this->current); } //当前位置 public function currentIdx() { return $this->current; }}/*}}}*/class Client{/*{{{*/ public static function main($argv) { //创建一个容器 $myAggregate = new MyAggregate(); //向容器中添加元素 $myAggregate->setItem(0,'张三'); $myAggregate->setItem(1,'李四'); $myAggregate->setItem(2,'王五'); //给容器创建迭代器 $iterator = $myAggregate->createIterator(); //遍历 while(!$iterator->isDone()) { $idx = $iterator->currentIdx(); $item = $iterator->currentItem(); echo "当前位置:{$idx},值:{$item}\r\n"; $iterator->next(); } }}/*}}}*/Client:: main($argv);?>
5 结果
1 0
- php迭代器模式
- 设计模式php实例:迭代器模式
- PHP設計模式之迭代器模式
- PHP设计模式漫谈之迭代器模式
- PHP设计模式-迭代器模式
- PHP设计模式-迭代器模式
- PHP设计模式之迭代器模式(Iterator)
- php中的设计模式之--迭代器模式
- PHP设计模式——迭代器模式
- php设计模式之迭代器模式
- PHP设计模式漫谈之迭代器模式
- php设计模式之迭代器模式
- PHP设计模式——迭代器模式
- php设计模式(迭代器模式)
- PHP 设计模式之迭代器模式
- PHP设计模式系列 - 迭代器
- PHP设计模式系列 - 迭代器
- php设计模式 四 (原型模式 迭代器模式)
- Java 反射机制
- LightOJ 1029 【最小生成树】
- 本人的嵌入式职业英文记录 - 第1周
- Linux设备口
- 从接口与抽象类说起
- php迭代器模式
- 在Python2.7里安装SOAPpy和问题解决
- Android ListView之高亮显示
- input元素添加监听事件
- iOS高级编程之安全机制,为你的App保驾护航
- jQuery对象与DOM对象之间的转换方法
- linux下终端命令快捷键
- 删除所有表,所有试图,所有序列,所有存储过程
- 正则表达式