设计模式——迭代器模式

说明

示例

下面看下代码实现

interface Collection{
public function iterator();
public function get(int $i);
public function size(): int;
}

interface Iterator{
public function previous();
public function next();
public function hasNext(): bool;
public function first();
}

class MyCollection implements Collection{
public string $str = 'ABCDE';
public function iterator(): MyIterator{
return new MyIterator($this);
}
public function get(int $i): string{
return $this->str[$i];
}
public function size(): int{
return strlen($this->str);
}
}

class MyIterator implements Iterator{
private Collection $collection;
private int $pos = -1;
public function __construct(Collection $collection){
$this->collection = $collection;
}

public function previous(){
if ($this->pos > 0){
$this->pos--;
}
return $this->collection->get($this->pos);
}

public function next(){
if ($this->pos < $this->collection->size() - 1){
$this->pos++;
}
return $this->collection->get($this->pos);
}

public function hasNext(): bool{
return $this->pos < $this->collection->size() - 1;
}

public function first(){
$this->pos = 0;
return $this->collection->get($this->pos);
}
}


// 调用
$collection = new MyCollection();
$it = $collection->iterator();
while ($it->hasNext()){
echo $it->next().'&nbsp;&nbsp;';
}
// output: A B C D E

总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
赏

留言

想法、疑问或勘误,都可以写在这里。留言会公开显示。

正在准备留言区…

 上一篇
软件的设计模式 软件的设计模式
设计模式的六大原则 总原则:开闭原则(Open Close Principle) 开闭原则就是说对扩展开放,对修改关闭。在程序需要进行拓展的时候,不能去修改原有的代码,而是要扩展原有代码,实现一个热插拔的效果。所以一句话概括就是:为了使程序
2022-05-19
下一篇 
设计模式——适配器模式 设计模式——适配器模式
说明 适配器模式将某个类的接口转换成客户端期望的另一个接口表示,目的是消除由于接口不匹配所造成的类的兼容性问题。主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。 分类 类的适配器模式 核心思想就是:有一个Source类,拥
2022-05-19