迭代器模式

概述

一个聚合对象,如一个列表(List)或者一个集合(Set),应该提供一种方法来让别人可以访问它的元素,而又不暴露它的内部结构。此外,针对不同的需要,可能还要以不同方式遍历整个聚合对象,但是我们不希望在聚合对象中充斥着各种不同遍历的操作。怎样遍历一个聚合对象,又不需要了解聚合对象的内部结构,还能提供多种不同的遍历方式,这就是迭代器模式所要解决的问题

迭代器模式中,提供一个外部的迭代器来对聚合对象进行访问和遍历,聚合对象只负责存储数据


模式分析

定义一个简单的迭代器接口

public interface MyIterator {
    void first();	// 访问第一个元素
    void next();	// 访问下一个元素
    boolean isLast();	// 判断是否是最后一个元素
    Object currentItem();	// 获取当前元素
}

定义一个聚合接口

public interface MyCollection {
    // 返回一个 MyIterator 迭代器对象
    MyIterator createIterator();
}

定义好抽象层之后,我们需要定义抽象迭代器接口和抽象聚合接口的实现类,一般将具体迭代器类作为具体聚合类的内部类,从而迭代器可以直接访问聚合类中的数据

public class NewCollection implements MyCollection {
    
    private Object[] obj = {"dog", "pig", "cat", "monkey", "pig"};
    
    public MyIterator createIterator() {
        return new NewIterator();
    }
    
    private class NewIterator implements MyIterator {
        
        private int currentIndex = 0;
        
        public void first() {
            currentIndex = 0;
        }
        
        public void next() {
            if(currentIndex < obj.length) {
                currentIndex++;
            }
        }
        
        public boolean isLast() {
            return currentIndex == obj.length;
        }
        
        public void currentItem() {
            return obj[currentIndex];
        }
    }     
}

NewCollection 类实现了 MyCollection 接口,实现了 createIterator() 方法,同时定义了一个数组用于存储数据元素,还定义了一个实现了 MyIterator 接口的内部类,索引变量 currentIndex 用于保存所操作的数组元素的下标值

测试代码如下:

public class Client {
    
    public static void process(MyCollection collection) {
        MyIterator i = collection.createIterator();
        while(!i.isLast()) {
            System.out.println(i.currentItem().toString());
            i.next();
        }
    }
    
    public static void main(String args[]) {
        MyCollection collection = new NewCollection();
        process(collection);
    }
}
posted @ 2020-05-25 15:57  低吟不作语  阅读(572)  评论(0编辑  收藏  举报