设计模式之迭代器模式,iterator

package liu.iterator.demo;
public abstract class Iterator {
 public abstract Object First();
 public abstract Object Next();
 public abstract Boolean IsDone();
 public abstract Object CurrentItem();
}
---------------------------------------
package liu.iterator.demo;
public class ConcreteIterator extends Iterator{
 private int current = 0;
 private ConcreteAggregate  aggregate;
 
 
 public ConcreteIterator(ConcreteAggregate aggregate){
  this.aggregate = aggregate;
 }
 @Override
 public Object First() {
  
  return aggregate.getElement(0);
 }
 @Override
 public Object Next() {
  Object ret = null;
  current++;
  if(current < aggregate.Count()){
   ret = aggregate.getElement(current);
  }
  return ret;
 }
 @Override
 public Boolean IsDone() {
  
  return current>=aggregate.Count()?true:false;
 }
 @Override
 public Object CurrentItem() {
  
  return aggregate.getElement(current);
 }
}

-----------------------------------------
package liu.iterator.demo;
public abstract class Aggregate {
 
 public abstract Iterator CreateIterator();
}

------------------------------------------
package liu.iterator.demo;
import java.util.ArrayList;
import java.util.List;
public class ConcreteAggregate extends Aggregate{
 private List<Object> items = new ArrayList<Object>();
 Object[] present = {"大鸟","小鸟","行李","小鸟","行李","小鸟","行李"};
 
 @Override
 public Iterator CreateIterator() {
  
  return new ConcreteIterator(this);
 }
 
 public int Count(){
  return present.length;
 }
 
 
  public Object getElement(int index){ //得到当前乘客的情况
   if(index<present.length){
   return present[index];
   }
   else{
   return null;
   }
   }
 
}

------------------------------------------ 
package liu.iterator.demo;
public class Main {
 private Iterator it;
 private Aggregate a = new ConcreteAggregate();
 public void operation(){
 it = a.CreateIterator(); //售票员开始点名
 while(!it.IsDone()){ //如果没点完
 System.out.println(it.CurrentItem().toString()); //获得被点到乘客的情况
 it.Next(); //点下一个
 }
 }
 public static void main(String agrs[]){
 Main test = new Main();
 test.operation();
 }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值