設計模式--迭代器模式

迭代器模式(iterator):java

順序訪問彙集中的對象。

示例:ide

迭代器模式測試類IteratorTest.java測試

/**
 * 迭代器模式測試類
 *
 * @author Kevin
 * @date 2016-3-15
 */
public class IteratorTest {

	public static void main(String[] args) {
		Collection collection = new CollectionImpl();
		Iterator iterator = collection.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
	}

}

迭代器接口類Iterator.javathis

/**
 * 迭代器接口
 *
 * @author Kevin
 * @date 2016-3-15
 */
public interface Iterator {

	/**
	 * 前移
	 *
	 * @author Kevin
	 */
	Object previous();

	/**
	 * 後移
	 *
	 * @author Kevin
	 */
	Object next();

	/**
	 * 判斷後面是否還有集合元素
	 *
	 * @author Kevin
	 */
	boolean hasNext();

	/**
	 * 取得第一個元素
	 *
	 * @author Kevin
	 */
	Object first();

}

集合接口Collection.javacode

/**
 * 集合接口
 *
 * @author Kevin
 * @date 2016-3-15
 */
public interface Collection {

	/**
	 * 獲取迭代器
	 *
	 * @author Kevin
	 */
	Iterator iterator();

	/**
	 * 獲取集合元素
	 *
	 * @author Kevin
	 */
	Object get(int index);

	/**
	 * 獲取集合大小
	 *
	 * @author Kevin
	 */
	int size();

}

迭代器實現類IteratorImpl.java對象

/**
 * 迭代器實現類
 *
 * @author Kevin
 * @date 2016-3-15
 */
public class IteratorImpl implements Iterator {

	/* 集合接口 */
	private Collection collection;

	/* 索引位置 */
	private int pos = -1;

	public IteratorImpl(Collection collection) {
		this.collection = collection;
	}

	@Override
	public Object previous() {
		if (pos > 0) {
			pos--;
		}
		return collection.get(pos);
	}

	@Override
	public Object next() {
		if (pos < (collection.size() - 1)) {
			pos++;
		}
		return collection.get(pos);
	}

	@Override
	public boolean hasNext() {
		if (pos < (collection.size() - 1)) {
			return true;
		}
		return false;
	}

	@Override
	public Object first() {
		pos = 0;
		return collection.get(pos);
	}
}

集合實現類CollectionImpl.java索引

/**
 * 集合實現類
 *
 * @author Kevin
 * @date 2016-3-15
 */
public class CollectionImpl implements Collection {

	private String string[] = {"A","B","C","D","E"};

	@Override
	public Iterator iterator() {
		return new IteratorImpl(this);
	}

	@Override
	public Object get(int index) {
		return string[index];
	}

	@Override
	public int size() {
		return string.length;
	}
}
相關文章
相關標籤/搜索