2019年5月13日 星期一

7天學會設計模式 CHAP16 走訪器模式 Iterator

7天學會設計模式
http://www.books.com.tw/products/0010750585

chap16.
走訪器模式 Iterator
目的:提供方法走訪集合內的物件,走訪過程不需知道集合內部的結構
package com.ssc24.chap16.demo01;
public interface Iterator<E> {
 boolean hasNext();
 E next();
}

package com.ssc24.chap16.demo01;
public class SimpleList {
 private int index = 0;
 private int size = 0;
 private String[] carList = new String[1000];
 public void add(String car) {
  carList[size] = car;
  size++;
 }
 public SimpleIterator getIterator() {
  return new SimpleIterator();
 }
 public class SimpleIterator implements Iterator {
  @Override
  public boolean hasNext() {
   if (index >= size) {
    return false;
   }
   return true;
  }
  public String next() {
   if (hasNext()) {
    return carList[index++];
   }
   throw new IndexOutOfBoundsException();
  }
 }
}

package com.ssc24.chap16.demo01;
import static org.junit.Assert.*;
import org.junit.Test;
public class SimpleListTest {
 @Test
 public void test() {
  System.out.println("===走訪器模式 測試===");
  SimpleList list = new SimpleList();
  list.add("樂高車");
  list.add("超跑");
  list.add("露營車");
  list.add("連結車");
  list.add("九門轎車");
  list.add("F1賽車");
  Iterator it = list.getIterator();
  while (it.hasNext()) {
   System.out.println(it.next());
  }
  it.next();
 }
}

/**
===走訪器模式 測試===
樂高車
超跑
露營車
連結車
九門轎車
F1賽車
**/