一、定义

提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

二、代码实例

*
需求

自己写一个iterator迭代器,遍历list。

*
代码实现

迭代器接口:
public interface Iterator { public Object first(); public Object next();
public boolean isDone(); public Object currentItem(); }
具体迭代类型接口:
public interface Aggregate { public Iterator createIterator(); }
迭代器实现类:
public class ConcreteIterator implements Iterator { private ConcreteAggregate
aggregate; private int current = 0; public ConcreteIterator(ConcreteAggregate
aggregate) { this.aggregate = aggregate; } @Override public Object first() {
return aggregate.get(0); } @Override public Object next() { Object result =
null; current++; if (current < aggregate.count()) { result =
aggregate.get(current); } return result; } @Override public boolean isDone() {
return current >= aggregate.count() ? true : false; } @Override public Object
currentItem() { return aggregate.get(current); } }
list迭代器实现类:
public class ConcreteAggregate implements Aggregate { private List<Object>
items = new ArrayList<>(); @Override public Iterator createIterator() { return
new ConcreteIterator(this); } public int count() { return items.size(); }
public Object get(int index) { return items.get(index); } public Object
add(Object value) { return items.add(value); } }
测试类:
public class Test { public static void main(String[] args) {
ConcreteAggregate aggregate = new ConcreteAggregate(); aggregate.add("张三");
aggregate.add("李四"); aggregate.add("王五"); aggregate.add("赵六");
aggregate.add("田七"); Iterator iterator = new ConcreteIterator(aggregate); while
(!iterator.isDone()) { System.out.println(iterator.currentItem() + ",请买票");
iterator.next(); } } }
 

技术
©2019-2020 Toolsou All rights reserved,
某东14薪变16薪,是诚意还是套路?HashMap详解os模块的简单使用html写樱花树,写樱花树的作文浏览器内核(理解)java四大函数式接口(重点,简单)让人意想不到的Python之樱花树(turtle库的华丽样式)计算机网络---计算机网络基本概念(协议、体系)06【若依框架解读】数据范围过滤--太牛了