设计模式之迭代器模式(iterator|Cursor)

迭代子模式又叫游标(Cursor)模式,是对象的行为模式。迭代子模式可以顺序的访问一个聚集中的元素而不必暴露聚集的内部表象(internal representation)。

Java 设计模式之迭代器模式(iterator|Cursor) 示例

  • 定义抽象迭代器
public interface MyIterator<T> {
	public T next();
	public boolean hasNext();
}
  • 定义具体迭代器
public class ConcreateIterator<T> implements MyIterator<T> {
	private List<T> mList;
	// 当前游标位置
	private int mCursor = 0;
	// 当前容器容量
	private int capacity = 0;

	public ConcreateIterator(List<T> list) {
		this.mList = list;
		if(mList != null && !mList.isEmpty())
		{
			this.capacity = mList.size();
		}
	}

	@Override
	public T next() {
		return mList.get(mCursor++);
	}

	@Override
	public boolean hasNext() {
		return mCursor + 1 <= capacity;
	}
}
  • 定义聚合抽象接口
public interface MyAggregate<T> {
	  public void add(T t);
	  public  void remove(T t);
	  public  MyIterator<T> iterator();
}
  • 定义具体聚合类
public class ConcreteAggregate<T> implements MyAggregate<T> {
	private List<T> mList = new ArrayList<>();
	@Override
	public void add(T t) {
		mList.add(t);
	}

	@Override
	public void remove(T t) {
		mList.remove(t);
	}

	@Override
	public MyIterator<T> iterator() {
		return new ConcreateIterator<>(mList);
	}
}
  • 测试
public class App {
	public static void main(String[] args)
	{
		MyAggregate<String> list = new ConcreteAggregate<>();
		list.add("a");
		list.add("b");

		MyIterator<String> it = list.iterator();
		while(it.hasNext())
		{
			LogHelper.log("value = " + it.next());
		}
	}
}

运行结果

【www.pangugle.com】-  value = a
【www.pangugle.com】-  value = b