设计模式之迭代器模式(行为型)

一、模式定义

迭代器模式(Iterator Pattern):提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor),所以迭代器模式是一种对象行为型。

二、模式角色

  • Iterator:抽象迭代器
  • ConcreteIterator:具体迭代器
  • Aggregate:抽象聚合类
  • ConcreteAggregate:具体聚合类

三、模式分析

对于迭代器模式来说,一个聚合可以有多个遍历。在迭代器模式中,提供了一个外部的迭代器对聚合对象进行访问和遍历,迭代器定义了一个访问聚合对象的接口,可以跟踪遍历元素,了解哪些元素已经遍历过而哪些没有。

迭代器模式中应用了工厂方法模式,聚合类充当工厂类,而迭代器充当产品类

****迭代器模式本质****

迭代器模式本质:将聚合对象存储的内部数据提取出来,封装到一个迭代器中,通过专门的迭代器来遍历聚合对象的内部数据,这就是迭代器模式的本质

****聚合对象主要职责****

聚合对象主要有两个职责:一是存储内部数据;二是遍历内部数据;最基本的职责还是存储内部数据

四、典型例子

例子来自:《设计模式》一书

自定义迭代器

自定义迭代器
Client:客户端调用
MyIterator:抽象迭代器
MyCollection:抽象聚合类
NewCollection:具体聚合类
NewIterator:具体迭代器

interface MyCollection
{
    MyIterator createIterator();
}
interface MyIterator
{
    void first();
    void next();
    boolean isLast();
    Object currentItem();
}

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 void previous()
    {
        if(currentIndex>0)
        {
            currentIndex--;
        }
    }   
    
    public boolean isLast()
    {
        return currentIndex==obj.length;
    }
    
    public boolean isFirst()
    {
        return currentIndex==0;
    }
    
    public Object currentItem()
    {
        return obj[currentIndex];
    }
    
   }
}

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 a[])
    {
        MyCollection collection=new NewCollection();
        process(collection);
    }
}

五、适用场景

在以下的情况可以使用迭代器模式:

  • 访问一个聚合对象的内容而无须暴露它的内部表示。
  • 需要为聚合对象提供多种遍历方式。
  • 为遍历不同的聚合结构提供一个统一的接口。

猜你喜欢

转载自www.cnblogs.com/mzq123/p/10703065.html