码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器模式

时间:2015-04-10 11:21:07      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

设计模式的意义在于:面向业务内容、业务数据结构和系统架构,高内聚低耦合、优雅的将平面逻辑立体化。

  1 package designPattern;
  2 
  3 /**
  4  * 迭代器模式
  5  * @author Administrator
  6  */
  7 public class B16_IteratorTest {
  8 
  9     /**
 10      *  给定一个语言,定义它的文法的一种表示,并定义一个解释器,
 11      *  这个解释器使用该表示来解释语言中的句子。
 12      */
 13     public static void main(String[] args) {
 14         List1 list = new List1Impl();
 15         list.add("a");
 16         list.add("b");
 17         list.add("c");
 18         //第一种迭代方式
 19         Iterator1 it = list.iterator();
 20         while (it.hasNext()) {
 21             System.out.println(it.next());
 22         }
 23         
 24         System.out.println("=====");
 25         //第二种迭代方式
 26         for (int i = 0; i < list.getSize(); i++) {
 27             System.out.println(list.get(i));
 28         }
 29     }
 30 }
 31 //iterator 迭代器定义访问和遍历元素的接口。
 32 interface Iterator1 {
 33 
 34     Object next();
 35     
 36     void first();
 37     
 38     void last();
 39     
 40     boolean hasNext();
 41 }
 42 //concreteIterator 具体迭代器实现迭代器接口。对该聚合遍历时跟踪当前位置。
 43 class IteratorImpl implements Iterator1 {
 44 
 45     private List1 list;
 46     
 47     private int index;
 48     
 49     public IteratorImpl(List1 list) {
 50         index = 0;
 51         this.list = list;
 52     }
 53     
 54     public void first() {
 55         index = 0;
 56     }
 57 
 58     public void last() {
 59         index = list.getSize();
 60     }
 61 
 62     public Object next() {
 63         Object obj = list.get(index);
 64         index++;
 65         return obj;
 66     }
 67 
 68     public boolean hasNext() {
 69         return index < list.getSize();
 70     }
 71 }
 72 //aggregate 聚合定义创建相应迭代器对象的接口。
 73 interface List1 {
 74 
 75     Iterator1 iterator();
 76     
 77     Object get(int index);
 78     
 79     int getSize();
 80     
 81     void add(Object obj);
 82 }
 83 //concreteAggregate 具体聚合实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例.
 84 class List1Impl implements List1 {
 85 
 86     private Object[] list;
 87     
 88     private int index;
 89     
 90     private int size;
 91     
 92     public List1Impl() {
 93         index = 0;
 94         size = 0;
 95         list = new Object[100];
 96     }
 97     
 98     public Iterator1 iterator() {
 99         return new IteratorImpl(this);
100     }
101     
102     public Object get(int index) {
103         return list[index];
104     }
105     
106     public int getSize() {
107         return this.size;
108     }
109     
110     public void add(Object obj) {
111         list[index++] = obj;
112         size++;
113     }
114 }

 

环境:JDK1.6,MAVEN,tomcat,eclipse

源码地址:http://files.cnblogs.com/files/xiluhua/designPattern.rar

欢迎亲们评论指教。

迭代器模式

标签:

原文地址:http://www.cnblogs.com/xiluhua/p/4413800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!