来自《Thinking in Java》
多的不说,直接上代码。
interface Selector {
boolean end();
Object current();
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() {
// TODO Auto-generated method stub
return items[i];
}
public void next() {
// TODO Auto-generated method stub
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.println(selector.current() + " ");
selector.next();
}
}
这个例子很简单,相信也不需要解释什么了。