博客
关于我
设计模式之迭代器模式
阅读量:361 次
发布时间:2019-03-04

本文共 2716 字,大约阅读时间需要 9 分钟。

迭代器模式 Iterator Pattern

目录

迭代器模式(Iterator Pattern)是一种行为设计模式,旨在将对容器中包含的内部对象的访问委托给外部类,并通过Iterator(遍历器)按顺序进行访问。这种模式能够有效地处理按顺序遍历聚集对象集合的需求。

概念

迭代器模式的核心目标是提供一种高效且安全的方式来遍历容器中的元素。传统的实现方式可能面临以下问题:

  • 容器类承担了太多功能,既要实现容器的基本操作(如添加、删除)又要提供遍历功能,容易引起混乱。
  • 遍历逻辑与容器的其他操作耦合,难以维护和扩展。

迭代器模式通过引入专门的遍历器接口,解耦了遍历逻辑和容器的实现细节。它适用于以下场景:

  • 需要按顺序访问容器中的元素。
  • 需要对容器的元素进行统一的操作(如排序、过滤等)。

角色和职责

迭代器模式的主要角色包括:

  • Iterator(遍历器接口):定义了实现遍历功能的基本方法,如hasNext()next()等。
  • ConcreteIterator(具体遍历器类):实现了Iterator接口,根据具体的容器实现遍历逻辑。
  • Aggregate(容器接口):定义了容器的基本操作,如获取元素、判断大小等,并提供创建Iterator的方法。
  • ConcreteAggregate(具体容器类):实现了Aggregate接口,对容器中的元素进行管理,并提供Iterator的创建。

通过这种方式,遍历器可以通过持有容器的引用来访问容器中的元素,而无需直接暴露容器的内部结构。

案例分析

以下是一个使用迭代器模式的典型案例:

#include 
#include
using namespace std;typedef int Object;class MyIterator {public: virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() = 0; virtual Object CurrentItem() = 0;};class Aggregate {public: virtual Object getItem(int index) = 0; virtual MyIterator* CreateIterator() = 0; virtual int GetSize() = 0;};class ConcreteIterator : public MyIterator {public: ConcreteIterator(Aggregate* aggregate) { _aggregate = aggregate; _currentIndex = 0; } ~ConcreteIterator() { _aggregate = NULL; _currentIndex = 0; } virtual void First() { _currentIndex = 0; } virtual void Next() { if (_currentIndex < _aggregate->GetSize()) { _currentIndex++; } } virtual bool IsDone() { return _currentIndex == _aggregate->GetSize(); } virtual Object CurrentItem() { return _aggregate->getItem(_currentIndex); }protected:private: int _currentIndex; Aggregate* _aggregate;};class ConcreteAggregate : public Aggregate {public: ConcreteAggregate(int size) { for (int i = 0; i < size; i++) { _objects[i] = "Object" + (i + 1); } } ~ConcreteAggregate() { delete[] _objects; } virtual Object getItem(int index) { return _objects[index]; } virtual MyIterator* CreateIterator() { return new ConcreteIterator(this); } virtual int GetSize() { return _size; }protected:private: Object* _objects; int _size;};void main() { // 创建一个容器 ConcreteAggregate* aggregate = new ConcreteAggregate(5); // 创建一个遍历器 MyIterator* iterator = aggregate->CreateIterator(); // 遍历容器中的元素 while (!iterator->IsDone()) { Object currentItem = iterator->CurrentItem(); cout << currentItem << " "; iterator->Next(); } // 释放资源 delete iterator; delete aggregate;}

总结

迭代器模式通过引入遍历器接口,成功地将遍历逻辑与容器的实现细节解耦。这种模式不仅提高了代码的可维护性和扩展性,还为容器的其他操作提供了更干净的接口。通过合理使用迭代器模式,可以在保证安全性的前提下,简化对容器内部结构的访问,充分发挥容器与遍历器之间的依赖关系。

转载地址:http://gaur.baihongyu.com/

你可能感兴趣的文章
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>
sqlserver学习笔记(三)—— 为数据库添加新的用户
查看>>
org.apache.http.conn.HttpHostConnectException: Connection to refused
查看>>
org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
查看>>
org.apache.ibatis.exceptions.PersistenceException:
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:processDebugManifest'
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.amqp.AmqpConnectException:java.net.ConnectException:Connection timed out:connect
查看>>
org.springframework.beans.factory.BeanDefinitionStoreException
查看>>
org.springframework.boot.context.properties.ConfigurationBeanFactoryMetadata
查看>>