public abstract class Component{ public abstract void operation(); public void add(Component component){}; public void remove(Component component){}; }
import java.util.*; public class Composite extends Component{ String name; ArrayList children = new ArrayList(); public Composite(String name){ this.name = name; } public void add(Component component){ children.add(component); } public void remove(Component component){ children.remove(component); } public void operation(){ System.out.println(name); Iterator iterator = children.iterator(); while(iterator.hasNext()){ Component child = (Component)iterator.next(); child.operation(); } } }
public class Leaf extends Component{ String name; public Leaf(String name){ this.name = name; } public void operation(){ System.out.println(name); } }
public boolean contains(Object o) { Iterator e = iterator(); if (o==null) { while (e.hasNext()) if (e.next()==null) return true; } else { while (e.hasNext()) if (o.equals(e.next())) return true; } return false; }
public Iterator iterator() { return new Itr(); //Itr是一个内部类 } private class Itr implements Iterator { int cursor = 0;//Iterator的计数器,指示当前调用next()方法时会被返回的元素的位置 int lastRet = -1;//指示刚刚通过next()或者previous()方法被返回的元素的位置,-1 //表示刚刚调用的是remove()方法删除了一个元素。
//modCount是定义在AbstractList中的字段,指示列表被修改的次数。Iterator用//这个值来检查其包装的列表是否被其他方法所非法修改。 int expectedModCount = modCount;
public boolean hasNext() { return cursor != size(); } public Object next() { try { //get方法仍然是一个抽象方法,依赖于具体的子类实现 Object next = get(cursor); //检查列表是否被不正确的修改 checkForComodification(); lastRet = cursor++; return next; } catch(IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); checkForComodification(); try { //同样remove(int)也依赖于具体的子类实现 AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch(IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }