ڼС
梦回起点
做你害怕做的事,你会发现:不过如此
本站基于WordPress—主题by 设计窝
冀ICP备15003737号
梦回起点
Copyright © 2015-2024 All rights reserved.

迭代器模式——大话设计模式读书笔记

迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。

迭代器模式的UML图如下:

迭代器模式

C++实现的代码:

/*
 * Copyright (c) 2017 initm.com All rights reserved.
 * 作者: Stupid
 * 描述: 迭代器模式模式
 * 完成时间: 2017-11-12 22:43
*/
#include <QCoreApplication>
#include <iostream>
#include <vector>
#include <new>

class Iterator
{
public:
    virtual int& First() = 0;
    virtual int& Next() = 0;
    virtual bool IsDone() = 0;
    virtual int& CurrentItem() = 0;
    virtual ~Iterator(){}
};

class Aggregate
{
public:
    virtual Iterator* CreateIterator() = 0;
    virtual int GetCount() = 0;
    virtual ~Aggregate(){}
};

class ConcreteAggregate: public Aggregate
{
private:
    std::vector<int> items;
    int count=0;
public:
    Iterator* CreateIterator();

    int GetCount(){
        return count;
    }
    int& operator[](const size_t& i){
        if(i >= items.size()){
            items.resize(i+1);
            count = items.size();
        }
        return items[i];
    }
};

class ConcreteIterator: public Iterator
{
private:
    ConcreteAggregate* aggregate;
    int current = 0;

public:
    ConcreteIterator(ConcreteAggregate* aggregate):aggregate(aggregate){}
    int& First()override final{
        return (*aggregate)[0];
    }
    int& Next()override final{
        current++;
        return (*aggregate)[current];
    }
    bool IsDone()override final{
        return current >= (*aggregate).GetCount()-1 ? true : false;
    }
    int& CurrentItem()override final{
        return (*aggregate)[current];
    }
};

Iterator* ConcreteAggregate::CreateIterator(){
    return new ConcreteIterator(this);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    ConcreteAggregate concreteAggregate;
    concreteAggregate[0] = 1;
    concreteAggregate[1] = 2;
    concreteAggregate[4] = 5;
    Iterator* it = concreteAggregate.CreateIterator();
    std::cout << it->First() << std::endl;
    while (!it->IsDone()){
        std::cout << it->Next() << std::endl;
    }
    return a.exec();
}

其实迭代器模式已经再常见不过了,STL里遍地是迭代器。

2017-11-12
                         
暂无评论

发表回复