酷愛生活、享受文娛、專注技術,歡迎關注QGer,我們1起見證成長!
甚么是迭代器模式?
官方解釋:to access the elements of an aggregate object sequentially without exposing its underlying implementation.
順序地訪問集合對象的元素并且不暴露它的內部實現
通俗解釋:假定給定1個集合對象,定義1個與之相干聯的Iterator(迭代器),該迭代器能夠訪問集合對象的內部元素,通過迭代的方法能夠依照順序順次訪問集合對象的每個元素。
為何使用迭代器模式?
如何使用迭代器模式?
UML圖以下:
各個組件解釋:
Iterator:抽象迭代器,定義了迭代器最基本的接口。如:hasNext()表示是不是該迭代是不是還有下1個元素,next則是返回迭代的下1個元素。
Aggregate:抽象集合,定義了集合的基本操作接口。如:add()向該集合增加1個原色,remove()則表示刪除某個元素。
ComcreteAggregate:具體數據集合類,定義了集合元素的結構,操作細節。同時在類內部定義了1個具體迭代器并提供1個能夠返回迭代器對象的方法。
ConcreteIterator:具體迭代器,通常定義在聚合類的內部,以此來到達訪問聚合類內部數據結構的目的,同時實現了迭代訪問聚合類元素的方法。
使用范圍:
當你想要在不暴露其內部表示的情況下訪問1個對象集合
當你想要有多種遍歷方式來遍歷1個對象集合,如正序、倒序、跳表訪問
利用舉例:
假定現在有1個學生對象集合類,客戶端其實不想關心其內部細節,只需要能遍歷學生對象(或學生對象的某些屬性)便可。使用迭代器模式來實現這個需求。
1、定義迭代器和集合的抽象接口。
interface Iterator<T> {
T next();
boolean hasNext();
}
interface Collection<T> {
boolean add(T element);
boolean remove(T element);
}
2、定義學生對象類,簡明起見,不定義太多復雜屬性
public class Student {
private String id;
private String name;
public Student(String id, String name) {
this.id = id;
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
}
3、實現具體學生對象聚合類,并在內部依賴定義具體迭代器。
public class StudentList implements Collection<Student> {
List<Student> elementList = new ArrayList<>();
@Override
public void add(Student element) {
elementList.add(element);
}
@Override
public boolean remove(Student element) {
return elementList.remove(element);
}
public Iterator<Student> createIterator(){
return new StudentIterator(elementList);
}
//具體迭代器類
private class StudentIterator implements Iterator<Student> {
private List<Student> students;
private int position;
public StudentIterator(List<Student> students) {
this.students = students;
this.position = 0;
}
@Override
public Student next() {
if(hasNext()) {
return students.get(position++);
}
return null;
}
@Override
public boolean hasNext() {
return position < students.size();
}
}
}
4、使用客戶端調用,此處mock1個測試數據,方便調用。
public class Client {
public static void main(String[] args) {
StudentList studentList = new StudentList();
studentList.add(new Student("001", "張3"));
studentList.add(new Student("002", "李4"));
studentList.add(new Student("004", "趙5"));
studentList.add(new Student("004", "錢6"));
Iterator<Student> iterator = studentList.createIterator();
while(iterator.hasNext()){
Student student = iterator.next();
System.out.println(student.getId() + student.getName());
}
}
}
注:此處的抽象迭代器、抽象集合接口,均只聲明了最簡單經常使用的方法,之際開發中可以根據需求增加各種各樣的方法,如Java.Util里面的Iterator定義接口以下:
迭代器則可以根據具體的聚合,選擇不同的遍歷方式:正序、倒序、跳表等。而遍歷的可以不是全部對象,也許你指向遍歷對象的某個屬性呢,如上例你指向要遍歷學生的學號,或說學號用得最勤勞,那末你另外定義1個迭代方法nextId來遍歷學生的學號呀。
上一篇 jdk 1.6 Internal Error (verifier.cpp:1524) guarantee(cp->cache() == NULL)
下一篇 [LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)