来源:自学PHP网 时间:2015-04-14 14:51 作者: 阅读:次
[导读] 这个Iterator就是收银台干的活。[html] package patterns.actions.iterator; public interface IteratorList { boolean isEmpty();//是否还有[hasNext()] Object nextMerchandise();//mer......
这个Iterator就是收银台干的活。
[html]
package patterns.actions.iterator;
public interface IteratorList {
boolean isEmpty();//是否还有[hasNext()]
Object nextMerchandise();//merchandise:商品
}
[java]
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;
}
}
[java]
package patterns.actions.iterator;
/**
* 购物的基本要素
* @author one
*
*/
public interface Shopping {
public void buy(Object obj);//买新的产品[add]
public IteratorList iteratorList();//结账[iterator]
}
[java]
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 ;
}
}
[java]
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());
}
}
}
输出结果:
[html]
可乐
|
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com