head first 设计模式笔记9-迭代器模式

迭代器模式:提供一种方法顺序访问一个集合对象中的各个元素,而又不暴露其内部的表示。

  迭代器接口

/**
 * @author oy
 * @date 2019年9月22日 上午9:03:08
 * @version 1.0.0
 */
public interface Iterator {
    boolean hasNext();
    Object next();
}
public class DinerMenuIterator implements Iterator {
    String[] items;
    int position = 0;
    
    public DinerMenuIterator(String[] items) {
        this.items = items;
    }
    
    public Object next() {
        String item = items[position];
        position += 1;
        return item;
    }
    
    public boolean hasNext() {
        if (position >= items.length || items[position] == null) {
            return false;
        } else {
            return true;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/xy-ouyang/p/11567782.html