ITeye博客

迭代子模式(Iterator)

ldaolong · 2014-10-14 17:19 · Design Patterns · 非技术 · Markdown

一、核心思想

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

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

 

关系图:

 

代码:

两个接口:

 

  1. public interface Collection {
  2. public Iterator iterator();
  3. /*取得集合元素*/
  4. public Object get(int i);
  5. /*取得集合大小*/
  6. public int size();
  7. }

 

  1. public interface Iterator {
  2. //前移
  3. public Object previous();
  4. //后移
  5. public Object next();
  6. public boolean hasNext();
  7. //取得第一个元素
  8. public Object first();
  9. }

两个实现:

 

  1. public class MyCollection implements Collection {
  2. public String string[] = {"A","B","C","D","E"};
  3. @Override
  4. public Iterator iterator() {
  5. return new MyIterator(this);
  6. }
  7. @Override
  8. public Object get(int i) {
  9. return string[i];
  10. }
  11. @Override
  12. public int size() {
  13. return string.length;
  14. }
  15. }

 

  1. public class MyIterator implements Iterator {
  2. private Collection collection;
  3. private int pos = -1;
  4. public MyIterator(Collection collection){
  5. this.collection = collection;
  6. }
  7. @Override
  8. public Object previous() {
  9. if(pos > 0){
  10. pos--;
  11. }
  12. return collection.get(pos);
  13. }
  14. @Override
  15. public Object next() {
  16. if(pos<collection.size()-1){
  17. pos++;
  18. }
  19. return collection.get(pos);
  20. }
  21. @Override
  22. public boolean hasNext() {
  23. if(pos<collection.size()-1){
  24. return true;
  25. }else{
  26. return false;
  27. }
  28. }
  29. @Override
  30. public Object first() {
  31. pos = 0;
  32. return collection.get(pos);
  33. }
  34. }

测试类:

 

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

 二、何时使用

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

优点:

简化了聚集的界面

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

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

 

 

三、java中的应用

Java集合类迭代子Iterator 和 Enumeration

JDBC查询数据集迭代子ResultSet

JSP分页

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。