Created
May 27, 2012 07:36
-
-
Save sanpingz/2802634 to your computer and use it in GitHub Desktop.
迭代器模式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static com.mceiba.util.Print.*; | |
interface Selector{ | |
boolean end(); | |
Object current(); | |
void next(); | |
} | |
public class Iterator{ | |
private Object[] items; | |
private int next = 0; | |
public Iterator(int size) { items = new Object[size]; } | |
public void add(Object obj){ | |
if(next < items.length) items[next++] = obj; | |
} | |
private class IteratorSelector 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 IteratorSelector(); } | |
public static void main(String[] args){ | |
Iterator iterator = new Iterator(10); | |
for(int i=0; i<10; i++) | |
iterator.add(Integer.toString(i)); | |
Selector selector = iterator.selector(); | |
while(!selector.end()){ | |
print(selector.current()+" "); | |
selector.next(); | |
} | |
println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment