设计模式-迭代器模式

朱雀 2023-07-11 12:53 283阅读 0赞

迭代器模式结构图

意图:提供一种方法顺序访问一个聚合对象中的各个元素,且不需要暴露该对象的内部表示。

主要解决:不同的方式来遍历整个整合对象。

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3d6ejk1MzIwMDQ2Mw_size_16_color_FFFFFF_t_70

其中:

  • Iterator定义访问和遍历元素的接口。
  • ConcreteIterator(具体迭代器)实现迭代器接口;对该聚合遍历时跟踪当前位置。
  • Aggregate(聚合)定义创建相应迭代器对象的接口。
  • ConcreteAggregate(具体聚合)实现创建相应迭代器的接口,该操作返回ConcreteIterator的一个适当的实例。

应用举例

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. //抽象迭代器类
  6. class Iterator
  7. {
  8. public:
  9. Iterator() {};
  10. virtual ~Iterator() {};
  11. virtual string First() = 0;
  12. virtual void Next() = 0;
  13. virtual string CurrentItem() = 0;
  14. virtual bool IsDone() = 0;
  15. };
  16. //具体迭代器
  17. class ConcreteIterator : public Iterator
  18. {
  19. public:
  20. ConcreteIterator(const vector<string> &t) { strlst = t; }
  21. string First()
  22. {
  23. return strlst.at(0);
  24. }
  25. void Next()
  26. {
  27. if (m_nCurrent < strlst.size())
  28. {
  29. m_nCurrent++;
  30. }
  31. }
  32. string CurrentItem()
  33. {
  34. return strlst[m_nCurrent];
  35. }
  36. bool IsDone()
  37. {
  38. return ((m_nCurrent == strlst.size()) ? true : false);
  39. }
  40. private:
  41. vector<string> strlst;
  42. int m_nCurrent = 0;
  43. };
  44. //抽象聚合类
  45. class Aggregate
  46. {
  47. public:
  48. virtual Iterator* CreateIterator() = 0;
  49. };
  50. //具体聚合类
  51. class ConcreteAggregate : public Aggregate
  52. {
  53. public:
  54. //创建迭代器
  55. Iterator* CreateIterator()
  56. {
  57. if (nullptr == m_pIterator)
  58. {
  59. m_pIterator = new ConcreteIterator(m_strLst);
  60. }
  61. return m_pIterator;
  62. }
  63. void Push(const string& strValue)
  64. {
  65. m_strLst.push_back(strValue);
  66. }
  67. private:
  68. Iterator* m_pIterator = nullptr;
  69. //存储的数据
  70. vector<string> m_strLst;
  71. };
  72. int main()
  73. {
  74. ConcreteAggregate c;
  75. c.Push("张三");
  76. c.Push("李四");
  77. c.Push("王二");
  78. auto iter = c.CreateIterator();
  79. while (!iter->IsDone())
  80. {
  81. cout << iter->CurrentItem() << endl;
  82. iter->Next();
  83. }
  84. getchar();
  85. return 0;
  86. }

适用性

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

发表评论

表情:
评论列表 (有 0 条评论,283人围观)

还没有评论,来说两句吧...

相关阅读

    相关 设计模式-模式

    > 迭代器模式结构图 意图:提供一种方法顺序访问一个聚合对象中的各个元素,且不需要暴露该对象的内部表示。 主要解决:不同的方式来遍历整个整合对象。  ![watermar

    相关 设计模式- 模式

    设计模式 - 迭代器模式 场景 小张的朋友开了一家酒店,最近新收购了一家庭旅馆。需要对自己酒店的房间和家庭旅馆的房间进行统一管理,但是两家之间都有各自的实现存储房间

    相关 设计模式——模式

    迭代器模式定义 提供一种方法访问一个容器对象中各个元素,而又不暴露该对象的内部细节。 使用场景 循环打印一个字符串集合,里面就用到了迭代器模式,迭代器的作用就是将