1.14(设计模式)迭代器模式

迭代器模式用于顺序访问集合对象的元素,而无需知道集合的底层表示,屏蔽了细节用一种更便携的方式访问集合对象。

定义一个获取迭代对象的接口

public interface Container {
    public Iterator getIterator();
}

定义迭代对象方法

public interface Iterator {
    public boolean hasNext();
    public Object next();
}

创建一个集合类时,需要在该集合类中添加一个内部类实现Iterator接口,用于判断是否有元素及获取元素。

集合类需要实现Container接口,提供一个获取实现了Iterator的内部类对象的方法,用于后续遍历。

//模拟集合类
public class NameRepository implements Container{
    
    private String[] names = {"hcf","zrx","gcmh"};
    
    
    //获取实现了Iterator接口的内部类
    @Override
    public Iterator getIterator() {
        // TODO Auto-generated method stub
        return new NameRepositoryIterator();
    }
    
    //集合内部实现Iterator接口的内部类。
    private class NameRepositoryIterator implements Iterator{
        
        private int index = (names != null && names.length > 0) ? 0 : -1;
        
        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub
            if(index < names.length) {
                return true;
            }else {
                return false;
            }
        }

        @Override
        public Object next() {
            // TODO Auto-generated method stub
            return names[index++];
        }
        
    }
}

Main

public class Main {
    public static void main(String[] args) {
        NameRepository nameRepository = new NameRepository();
        Iterator ite = nameRepository.getIterator();
        while(ite.hasNext()) {
            System.out.println(ite.next());
        }
    }
}
运行结果:
hcf
zrx
gcmh

参考资料:

https://www.runoob.com/design-pattern/iterator-pattern.html

原文地址:https://www.cnblogs.com/huang-changfan/p/10997637.html