设计模式-行为型-迭代器模式
大约 1 分钟
1、定义
迭代器模式:一种遍历访问容器对象中各个元素的方法,不暴露该对象内部结构
写法
/**
* 迭代器模式
*/
public interface Iterator<T> {
/**
* 是否有下一个元素
* @return
*/
boolean hasNext();
/**
* 返回当前元素,并将位置移至下一位
*/
T next();
}
public interface Collection<T> {
Iterator<T> iterator();
}
/**
* list列表迭代
* @param <T>
*/
public class ListIterator<T> implements Iterator<T>{
private List<T> array;
private int position;
public ListIterator(List<T> list){
this.array = list;
position = 0;
}
@Override
public boolean hasNext() {
return !(position > array.size() -1 || array.get( position ) == null);
}
@Override
public T next() {
T element = array.get( position );
position ++ ;
return element;
}
}
/**
* 雇员
*/
public class Employee {
private String name;// 姓名
private int age;// 年龄
private String sex;// 性别
private String position;// 职位
public Employee(String name, int age, String sex, String position) {
this.name = name;
this.age = age;
this.sex = sex;
this.position = position;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", position='" + position + '\'' +
'}';
}
}
/**
* 公司
*/
public class CompanyLi implements Collection<Employee>{
private Iterator<Employee> iterator;
public CompanyLi(){
List<Employee> list = new ArrayList<>( );
list.add(new Employee("小民", 26, "男", "程序猿"));
list.add(new Employee("小芸", 22, "女", "测试"));
list.add(new Employee("小方", 18, "女", "测试"));
list.add(new Employee("可儿", 21, "女", "设计"));
iterator = new ListIterator<>( list );
}
@Override
public Iterator<Employee> iterator() {
return iterator;
}
}
/**
*
* 迭代器模式
*
* 遍历又不暴露细节
*
* 支持对容器对象的多种遍历。弱化了容器类与遍历算法之间的关系
*
*/
public class TestMain {
public static void main(String[] args) {
CompanyLi companyLi = new CompanyLi();
//迭代
Iterator iterator = companyLi.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next().toString());
}
}
}
代码示例
https://github.com/yinlingchaoliu/23-design-pattern