欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java使用設(shè)計模式中迭代器模式構(gòu)建項(xiàng)目的代碼結(jié)構(gòu)示例

 更新時間:2016年05月03日 09:37:34   作者:匆忙擁擠repeat  
這篇文章主要介紹了Java使用設(shè)計模式中迭代器模式構(gòu)建項(xiàng)目的代碼結(jié)構(gòu)示例,迭代器模式能夠?qū)υL問者隱藏對象的內(nèi)部細(xì)節(jié),需要的朋友可以參考下

迭代器(Iterator)模式,又叫做游標(biāo)(Cursor)模式。GOF給出的定義為:提供一種方法訪問一個容器(container)對象中各個元素,而又不需暴露該對象的內(nèi)部細(xì)節(jié)。
 
迭代器模式由以下角色組成:
迭代器角色(Iterator):迭代器角色負(fù)責(zé)定義訪問和遍歷元素的接口。
具體迭代器角色(Concrete Iterator):具體迭代器角色要實(shí)現(xiàn)迭代器接口,并要記錄遍歷中的當(dāng)前位置。
容器角色(Container):容器角色負(fù)責(zé)提供創(chuàng)建具體迭代器角色的接口。
具體容器角色(Concrete Container):具體容器角色實(shí)現(xiàn)創(chuàng)建具體迭代器角色的接口。這個具體迭代器角色與該容器的結(jié)構(gòu)相關(guān)。

Java實(shí)現(xiàn)示例
類圖:

20165393304786.jpg (754×748)

代碼:

/** 
 * 自定義集合接口, 類似java.util.Collection 
 * 用于數(shù)據(jù)存儲 
 * @author stone 
 * 
 */ 
public interface ICollection<T> { 
   
  IIterator<T> iterator(); //返回迭代器 
  void add(T t); 
  T get(int index); 
} 
/** 
 * 自定義迭代器接口 類似于java.util.Iterator 
 * 用于遍歷集合類ICollection的數(shù)據(jù) 
 * @author stone 
 * 
 */ 
public interface IIterator<T> { 
  boolean hasNext(); 
  boolean hasPrevious(); 
  T next(); 
  T previous(); 
} 
/** 
 * 集合類, 依賴于MyIterator 
 * @author stone 
 */ 
public class MyCollection<T> implements ICollection<T> { 
 
  private T[] arys; 
  private int index = -1; 
  private int capacity = 5; 
   
  public MyCollection() { 
    this.arys = (T[]) new Object[capacity]; 
  } 
   
  @Override 
  public IIterator<T> iterator() { 
    return new MyIterator<T>(this); 
  } 
   
  @Override 
  public void add(T t) { 
    index++; 
    if (index == capacity) { 
      capacity *= 2; 
      this.arys = Arrays.copyOf(arys, capacity); 
       
    } 
    this.arys[index] = t; 
  } 
   
  @Override 
  public T get(int index) { 
    return this.arys[index]; 
  } 
   
} 


/* 
 * 若有新的存儲結(jié)構(gòu),可new 一個ICollection, 對應(yīng)的 new 一個IIterator來實(shí)現(xiàn)它的遍歷 
 */ 
@SuppressWarnings({"rawtypes", "unchecked"}) 
public class Test { 
  public static void main(String[] args) { 
    ICollection<Integer> collection = new MyCollection<Integer>(); 
    add(collection, 3, 5, 8, 12, 3, 3, 5); 
    for (IIterator<Integer> iterator = collection.iterator(); iterator.hasNext();) { 
      System.out.println(iterator.next()); 
    } 
     
    System.out.println("-------------"); 
     
    ICollection collection2 = new MyCollection(); 
    add(collection2, "a", "b", "c", 3, 8, 12, 3, 5); 
    for (IIterator iterator = collection2.iterator(); iterator.hasNext();) { 
      System.out.println(iterator.next()); 
    } 
     
  } 
   
  static <T> void add(ICollection<T> c, T ...a) { 
    for (T i : a) { 
      c.add(i); 
    } 
  } 
} 

打?。?/p>

3 
5 
8 
12 
3 
3 
5 
------------- 
a 
b 
c 
3 
8 
12 
3 
5 

相關(guān)文章

最新評論