迭代子模式(Iterator)

一、核心思想

迭代子模式又称Cursor模式,是对象的行为模式。迭代子模式可以顺序地访问聚集中的对象而不必显露聚集的内部对象。

包含:聚集对象 和 迭代器对象。

 

关系图:

 

代码:

两个接口:

 
  1. public interface Collection {  
  2.       
  3.     public Iterator iterator();  
  4.       
  5.     /*取得集合元素*/  
  6.     public Object get(int i);  
  7.       
  8.     /*取得集合大小*/  
  9.     public int size();  
  10. }  
 
  1. public interface Iterator {  
  2.     //前移  
  3.     public Object previous();  
  4.       
  5.     //后移  
  6.     public Object next();  
  7.     public boolean hasNext();  
  8.       
  9.     //取得第一个元素  
  10.     public Object first();  
  11. }  

两个实现:

 
  1. public class MyCollection implements Collection {  
  2.   
  3.     public String string[] = {"A","B","C","D","E"};  
  4.     @Override  
  5.     public Iterator iterator() {  
  6.         return new MyIterator(this);  
  7.     }  
  8.   
  9.     @Override  
  10.     public Object get(int i) {  
  11.         return string[i];  
  12.     }  
  13.   
  14.     @Override  
  15.     public int size() {  
  16.         return string.length;  
  17.     }  
  18. }  
 
  1. public class MyIterator implements Iterator {  
  2.   
  3.     private Collection collection;  
  4.     private int pos = -1;  
  5.       
  6.     public MyIterator(Collection collection){  
  7.         this.collection = collection;  
  8.     }  
  9.       
  10.     @Override  
  11.     public Object previous() {  
  12.         if(pos > 0){  
  13.             pos--;  
  14.         }  
  15.         return collection.get(pos);  
  16.     }  
  17.   
  18.     @Override  
  19.     public Object next() {  
  20.         if(pos<collection.size()-1){  
  21.             pos++;  
  22.         }  
  23.         return collection.get(pos);  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean hasNext() {  
  28.         if(pos<collection.size()-1){  
  29.             return true;  
  30.         }else{  
  31.             return false;  
  32.         }  
  33.     }  
  34.   
  35.     @Override  
  36.     public Object first() {  
  37.         pos = 0;  
  38.         return collection.get(pos);  
  39.     }  
  40.   
  41. }  

测试类:

 
  1. public class Test {  
  2.   
  3.     public static void main(String[] args) {  
  4.         Collection collection = new MyCollection();  
  5.         Iterator it = collection.iterator();  
  6.           
  7.         while(it.hasNext()){  
  8.             System.out.println(it.next());  
  9.         }  
  10.     }  
  11. }  

 二、何时使用

迭代子的作用就是用来方便查询一个集合中的数据。

优点:

简化了聚集的界面

因为每一个聚集对象可以有多个迭代子对象,每个迭代子状态时独立的。

由于遍历算法被封装在迭代子角色里,因此迭代的算法可以独立于聚集对象。

 

 

三、java中的应用

Java集合类迭代子Iterator 和 Enumeration

JDBC查询数据集迭代子ResultSet

JSP分页

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值