标签:
Collection接口,主要是返回一个迭代器iterator
public interface Collection { void add(Object o); int size(); Iterator iterator(); }
Iterator接口:
问题:为什么不把Iterator的两个方法放在Collection中,主要是为了接口隔离,Collection和Iterator变化互补影响。
public interface Iterator { Object next(); boolean hasNext(); }
ArrayList实现Collection接口
public class ArrayList implements Collection { Object[] objects = new Object[10]; int index = 0; public void add(Object o) { if(index == objects.length) { Object[] newObjects = new Object[objects.length * 2]; System.arraycopy(objects, 0, newObjects, 0, objects.length); objects = newObjects; } objects[index] = o; index ++; } public int size() { return index; } public Iterator iterator() { return new Iterator(){ private int currentIndex = 0; public boolean hasNext() { if(currentIndex >= index) return false; else return true; } public Object next() { Object o = objects[currentIndex]; currentIndex ++; return o; } }; } }
LinkedList同样实现Collection接口
public class LinkedList implements Collection { Node head = null; Node tail = null; int size = 0; public void add(Object o) { Node n = new Node(o, null); if(head == null) { head = n; tail = n; } tail.setNext(n); tail = n; size ++; } public int size() { return size; } public Iterator iterator() { //省略实现 return null; } } class Node { //省略getter,setter,和构造方法 private Object data; private Node next; }
Test方法
public static void main(String[] args) { Collection c = new ArrayList(); for(int i=0; i<15; i++) { c.add(new Cat(i)); } System.out.println(c.size()); Iterator it = c.iterator(); while(it.hasNext()) { Object o = it.next(); System.out.print(o + " "); } System.out.println(); }
备注:这个只是简单的模拟,jdk中使用的是泛型,自己有兴趣可以扩充。这种设计模式现实中很少用,大家可以参考jdk集合类的这部分代码了解迭代器模式。
标签:
原文地址:http://my.oschina.net/u/2361475/blog/506312