設計模式:迭代器模式(Iterator Pattern)
阿新 • • 發佈:2019-01-12
/** * 迭代器模式。 * @author Bright Lee */ public class IteratorPattern { public static void main(String[] args) { String[] strings = new String[] { "紅燒肉", "魚香肉絲", "毛血旺" }; Iterator<String> it = new StringIterator(strings); while (it.hasNext()) { String string = it.next(); System.out.println(string); } } } /** * 迭代器介面。 */ interface Iterator<T> { public boolean hasNext(); public T next(); } /** * 迭代器。 */ class StringIterator implements Iterator<String> { private int index; private String[] strings; public StringIterator(String[] strings) { this.strings = strings; this.index = 0; } public boolean hasNext() { if (index >= strings.length) { return false; } return true; } public String next() { String string = strings[index]; index++; return string; } }
執行結果:
紅燒肉
魚香肉絲
毛血旺