设计模式--迭代器模式

迭代器模式(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;
	}
}
相关文章
相关标签/搜索