• 设计模式-迭代器模式-笔记


    动机(Motivaton)

    在软件构建过程中,集合对象内部结构常常变化各异。但对于这些集合对象,我们呢希望在不暴露其内部结构的同时,可以让外部客户代码透明地访问其中包含的元素;同时这种“透明遍历”也为“同一种算法在多种集合对象上进行操作”提供了可能。

    使用面向对象技术将这种遍历机制抽象为“迭代器对象”为“应对变化中集合对象”提供一种优雅的方式。

    模式定义:

    提供一种方法顺序访问一个集合对象中的各个元素,而又不暴露(稳定)该对象内部表示。

    1. #include
    2. template<typename T>
    3. class Iterator {
    4. public:
    5. virtual void first() = 0;
    6. virtual void next() = 0;
    7. virtual bool isDone() = 0;
    8. virtual T& current() = 0;
    9. };
    10. template<typename T>
    11. class MyCollection {
    12. public:
    13. Iterator* GetIterator() {
    14. //...
    15. }
    16. };
    17. template<typename T>
    18. class CollentionIterator : public Iterator {
    19. MyCollection mc;
    20. public:
    21. CollentionIterator(const MyCollection& c) : mc(c) {}
    22. void first() override {
    23. //...
    24. }
    25. void next() override {
    26. //...
    27. }
    28. void isDone() override {
    29. //...
    30. }
    31. T& current() override {
    32. //...
    33. }
    34. };
    35. int main() {
    36. MyCollection<int> mc;
    37. Iterator<int>* iter = mc.GetIterator();
    38. for (iter->first(); !iter->isDone(); iter->next()) {
    39. std::cout << iter->current() << std::endl;
    40. }
    41. }

    要点总结:

    迭代抽象:访问一个集合对象的内容而无需暴露他的内部表示;

    迭代多态:为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的结构上进行操作;

    迭代器的健壮性考虑:遍历的同时更改迭代器所在集合机构,会导致问题。

  • 相关阅读:
    快来看看用FPGA做的开源示波器(二)
    【通道注意力机制】SENet
    SubGHz, LoRaWAN, NB-IoT, 物联网
    宝贝快出生的这三个表现,孕妈尽快去医院待产
    ROS定时器回调
    1010 一元多项式求导
    【计算机网络】应用层——HTTPS协议
    南大通用GBase 8a MPP Cluster大规模并行计算技术介绍
    【C语言】指针和数组笔试题解析(1)
    【机器学习算法】决策树-4 CART算法和CHAID算法
  • 原文地址:https://blog.csdn.net/zhaodongdong2012/article/details/134517604