欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

迭代器模式

程序员文章站 2022-05-23 11:37:59
...


摘自 《Java编程思想》第四版


 

/**
 * 迭代器模式
 * 
 * 利用非静态内部类可以访问外部类的特性
 * 
 * 摘自 Java编程思想 P192
 */

interface Selector{
	public boolean end();
	public Object current();
	public void next();
}

public class Sequence {

	private Object[] items;
	private int next = 0;
	public Sequence(int size){
		items = new Object[size];
	}
	public void add(Object x){
		if(next < items.length)
			items[next++] = x;
	}
	
	//内部类
	private class SequenceSelector implements Selector
	{
		private int i = 0;
		
		public boolean end() {
			return i==items.length;
		}

		public Object current() {
			return items[i];
		}

		public void next() {
			if(i<items.length)
				i++;
		}
	}
	
	public Selector selector()
	{
		return new SequenceSelector();
	}
	
	public static void main(String[] args) {
		Sequence sequence = new Sequence(10);
		for (int i = 0; i < 10; i++) {
			sequence.add(Integer.toString(i));
		}
		Selector selector = sequence.selector();
		while(!selector.end())
		{
			System.out.print(selector.current() + " ");
			selector.next();
		}
	}
}