迭代器設計模式爲我們提供一種順序訪問容器內部元素的方法,並且同時不對外暴露出內部的結構。
實現迭代器需要繼承Ierrator接口,並且覆寫hasNext和next方法。還可以覆寫remove方法。
例如:
package designPattern;
import java.util.Iterator;
/**
* Created by 18760 on 2017/11/23.
*/
class ABC{
String name;
public ABC(String name){
this.name = name;
}
public String toString(){ return this.name;}
}
class Menu implements Iterator{
ABC[] context;
int position = 0;
public Menu(ABC[] context){
this.context = context;
}
public Object next(){
ABC object = context[position];
position++;
return object;
}
public boolean hasNext(){
if (position>=context.length){
return false;
}
if (context[position]==null){
return false;
}
return true;
}
public void remove(){
if (position <= 0) {
throw new IllegalStateException("You can't remove've done at least one next()");
}
if (context[position - 1] != null) {
for (int i = position-1; i < (context.length - 1); i++) {
context[i] = context[i + 1];
}
context[context.length - 1] = null;
}
}
}
public class Iter {
public static void main(String[] args){
ABC a = new ABC("ASFD");
ABC b = new ABC("ASDFKJ");
ABC c = new ABC("sfgasdg");
ABC d = new ABC("ASDG");
ABC[] context = {a, b, c, d};
Menu menu = new Menu(context);
while (menu.hasNext()){
System.out.println((ABC)menu.next());
int i = 1;
if (i==1){
menu.remove();
i = i + 1;
}
}
}
}