Design Pattern | Iterator Pattern
by Botao Xiao
Iterator Pattern 迭代器模式
提供一种方法顺序的访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。 一般情况,我们自己开发时很少自定义迭代器,因为java本身已经把迭代器做到内部中了(比如:常用的list和set中都内置了迭代器)。 当然,如果真有这种需求需要我们自定义迭代器的话,可以参考jdk的迭代器实现方式来实现自己的迭代器。
Iterator Pattern 实现机制
public class MyIterable<T> implements Iterable<T> {
private Node<T> dummy;
private int length;
private Node<T> head;
private Node<T> tail;
public MyIterable() {
this.dummy = new Node<T>(null);
tail = head = dummy;
}
@Override
public Iterator<T> iterator() {
return new MyIterator<T>();
}
@SuppressWarnings("hiding")
private class MyIterator<T> implements Iterator<T>{
@SuppressWarnings("unchecked")
private MyIterable<T>.Node<T> current = (MyIterable<T>.Node<T>) dummy;
@Override
public boolean hasNext() {
return current.next != null;
}
@Override
public T next() {
T result = (T) current.next.t;
current = current.next;
return result;
}
}
private class Node<T>{ //定义一个内部的数据结构,用于承载对象。
T t;
Node<T> next;
Node<T> pre;
public Node(T t){
this.t = t;
}
}
public void add(T t){ //定义对于数据结构的操作方法
Node<T> newNode = new Node<>(t);
if(this.length == 0){
dummy.next = newNode;
newNode.pre = dummy;
this.head = dummy.next;
this.tail = this.head;
}else{
newNode.pre = tail;
tail.next = newNode;
tail = newNode;
}
this.length++;
}
public void remove(T t){
Node<T> current = this.dummy;
while(current.next != null){
current = current.next;
if(current.t.equals(t)){
current.pre.next = current.next;
}
}
}
public static void main(String[] args) {
MyIterable<Integer> it = new MyIterable<>();
it.add(1);
it.add(2);
it.add(3);
it.add(4);
it.add(5);
// for(Integer i : it){
// System.out.println(i);
// }
// Iterator<Integer> iterator = it.iterator();
// while(iterator.hasNext()){
// System.out.println(iterator.next());
// }
it.remove(5);
for(Integer i : it){
System.out.println(i);
}
}
}
Subscribe via RSS