浅析Java设计模式——迭代器模式

浅析Java设计模式——迭代器模式

本文介绍行为型模式的一种模式——迭代器模式。该模式主要用于对某一对象集合进行遍历,将对象的数据存储和遍历进行分离。在Java语言中有着较高的应用频率。

1、定义:提供一种方法顺序地访问一个聚合对象中的各个元素而不需要暴露该对象的内部表示。

2、模式结构:

(1)Iterator(抽象迭代器):定义访问和遍历元素的接口,声明获取元素的方法。

(2)ConcreteIterator(具体迭代器):实现抽象迭代器接口,完成遍历并跟踪元素当前位置。

(3)Aggregate(抽象聚合类):存储对象,创建迭代器对象的接口,声明创建迭代器对象的方法。

(4)ConcreteAggregate(具体聚合类):实现创建迭代器对象的接口,实现其方法。

3、案例分析:

(1)迭代器接口 MyIterator

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

(2)聚合接口 MyCollection

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

(3)具体聚合类 AniCollection

public class AniCollection implements MyCollection
{
    public MyIterator createIterator()
    {
        return new AniIterator();
    }
}

(4)具体迭代器类 AniIterator

public class AniIterator implements MyIterator
{
    private Object [] obj = {"dog","pig","cat","monkey"};
    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 Object currentItem()
    {
        return obj[currentIndex];
    }
 }

(5)测试类 Client

public class Client
{
    public static void process(MyCollection collection)
    {
        MyIterator it = collection.createIterator();
        while(!it.isLast())
        {
            System.out.println(it.currentItem().toString());
            it.next();
        }
    }

    public static void main(String [] args)
    {
        MyCollection collection = new AniCollection();
        process(collection);
    }
}

运行结果:

4、模式优缺点:

(1)优点:可以以不同的方式遍历一个聚合对象;同一个聚合上可以有多个遍历。

(2)缺点:增加新的聚合类需要对应增加新的迭代器类。

5、模式应用:

JDK 中的 Collection 接口中有方法 iterator()就是用于返回一个迭代器对象,来遍历集合的所有元素。一般我们很少自己定义迭代器,使用JDK内置的迭代器就可以了。



猜你喜欢

转载自blog.csdn.net/qq_38190057/article/details/80476342
今日推荐