这个Iterator就是收银台干的活。
package patterns.actions.iterator; public interface IteratorList { boolean isEmpty();//是否还有[hasNext()] Object nextMerchandise();//merchandise:商品 }
package patterns.actions.iterator; /** * 收银台清点商品 * @author one * */ public class IteratorCheck implements IteratorList { private Supermarket shop; private int total=0; private int current=0; IteratorCheck(Supermarket shop){ this.shop=shop; this.total=shop.size(); this.current=0; } @Override public boolean isEmpty() { return this.current<this.total; } @Override public Object nextMerchandise() { if(this.current<this.total) return this.shop.take(this.current++); return null; } }
package patterns.actions.iterator; /** * 购物的基本要素 * @author one * */ public interface Shopping { public void buy(Object obj);//买新的产品[add] public IteratorList iteratorList();//结账[iterator] }
package patterns.actions.iterator; import java.util.ArrayList; import java.util.List; /** * 超市提供具体的购物环境 * * @author one * */ public class Supermarket implements Shopping { private List cart = new ArrayList();// 购物车作为容器 @Override public void buy(Object obj) { cart.add(obj);// 将商品放到购物车 } @Override public IteratorList iteratorList() { return new IteratorCheck(this); } public int size() { return this.cart.size(); } public Object take(int current) { if(current<this.cart.size()) return this.cart.get(current); return null ; } }
package patterns.actions.iterator; public class Client { /** * @param args */ public static void main(String[] args) { Shopping cart = new Supermarket(); cart.buy("可乐"); cart.buy("果汁"); cart.buy("酸梅"); IteratorList check = cart.iteratorList(); while (check.isEmpty()) { System.out.println(check.nextMerchandise()); } } }
输出结果:
可乐 果汁 酸梅