介绍
行为设计模式之一,当想提供一个方法顺序遍历容器中的每个元素,而又不想暴露该对象的内部表示的时候可以使用迭代器模式。
使用场景
遍历一个容器对象的时候。
简单实现
小民跟小辉帮老板统计各部门的员工的信息。
1 2 3 4 5 6 7
| public interface Iterator {
boolean hasNext();
Object next();
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class MinIterator implements Iterator {
private List<Employee> list = new ArrayList<>(); private int position;
@Override public boolean hasNext() { return !(position>list.size()-1||list.get(position)==null); }
@Override public Object next() { Employee e = list.get(position); position++; return e; }
public MinIterator(List<Employee> list) { this.list = list; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class HuiIterator implements Iterator { private Employee[] array; private int position;
@Override public boolean hasNext() { return !(position>array.length-1||array[position]==null); }
@Override public Object next() { return array[position++]; }
public HuiIterator(Employee[] array) { this.array = array; }
}
|
1 2 3 4
| public interface Company {
Iterator iterator(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class CompanyMin implements Company {
private List<Employee> list = new ArrayList<>();
public CompanyMin() { list.add(new Employee("xiaomi","chengxuyuan","nan",96)); list.add(new Employee("dami","shoupiaoyuan","nv",90)); list.add(new Employee("gaoliang","chihuo","nv",88)); list.add(new Employee("bangzi","nongmin","nan",77)); }
@Override public Iterator iterator() { return new MinIterator(list); }
public List<Employee> getEmployees(){ return list; }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class CompanyHui implements Company {
private Employee[] array = new Employee[3];
public CompanyHui() { array[0]=new Employee("lili","xiaojie","nv",20); array[1]=new Employee("lisa","yaofande","nv",96); array[2]=new Employee("meimei","gongzhu","nv",96); }
@Override public Iterator iterator() { return new HuiIterator(array); }
public Employee[] getEmployees(){ return array; }
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public class Boss {
public static void main(String[] args){
CompanyMin companyMin=new CompanyMin(); check(companyMin.iterator());
CompanyHui companyHui = new CompanyHui(); check(companyHui.iterator());
}
private static void check(Iterator iterator) {
while(iterator.hasNext()){
System.out.println(iterator.next().toString()); } } }
|
上述的例子只是一个假设,在所谓的自定义的容器类的内部有使用了Java本身所提供的数据结构来存储数据,这也算是一种不恰当地实现方式,因为饿迭代器模式的规定不像其他的模式那么严格,实现也因人而异,好在大部分的高级语言类都为我们提供了相应的迭代器而不需要开发者自己去实现。
上一篇:责任链模式
下一篇:享元模式