Iterator pattern can ignore set object combination method, always use hasNext method to see if there's continues object and use next method to get the following object, it gives a more standard way to list all the objects.
Each object container we create one iterator class to implement Iterator interface, fulfill hasNext and next methods,
/**
* @Author Carter Deng
* @Date 2021/11/21
*/
public class InfoScienceIterator implements Iterator {
List<Department> departmentList;
int position;
public InfoScienceIterator(List<Department> departmentList) {
this.departmentList = departmentList;
this.position = 0;
}
@Override
public boolean hasNext() {
if (departmentList.size() > position + 1) {
return true;
}
return false;
}
@Override
public Object next() {
if (hasNext()) {
this.position++;
return departmentList.get(position);
}
return null;
}
}
/**
* @Author Carter Deng
* @Date 2021/11/21
*/
public class ComputerIterator implements Iterator {
Department[] departments;
int position;
public ComputerIterator(Department[] departments) {
this.departments = departments;
this.position = 0;
}
@Override
public boolean hasNext() {
if (this.departments != null) {
if (this.departments.length - 1 > position) {
return true;
}
}
return false;
}
@Override
public Department next() {
if (hasNext()) {
this.position++;
return departments[position];
}
return null;
}
}
Object container provides one method to return its corssponding iterator object,
/**
* @Author Carter Deng
* @Date 2021/11/21
*/
public class InfoScienceCollege implements College {
@Override
public Iterator createIterator() {
return new InfoScienceIterator(departments);
}
}
/**
* @Author Carter Deng
* @Date 2021/11/21
*/
public class ComputerCollege implements College {
@Override
public Iterator createIterator() {
return new ComputerIterator(departments);
}
}
When we want to list down all items in object container, we can ask object to return iterator object and use hasNext/Next methods.
/**
* @Author Carter Deng
* @Date 2021/11/22
*/
public class Test {
public static void main(String[] args) {
ComputerCollege computerCollege = new ComputerCollege();
InfoScienceCollege infoScienceCollege = new InfoScienceCollege();
Iterator computerCollegeIterator = computerCollege.createIterator();
Iterator infoScienceCollegeIterator = infoScienceCollege.createIterator();
while(computerCollegeIterator.hasNext()){
System.out.println(computerCollegeIterator.next());
}
System.out.println("=============================");
while(infoScienceCollegeIterator.hasNext()){
System.out.println(infoScienceCollegeIterator.next());
}
}
}