码迷,mamicode.com
首页 > 其他好文 > 详细

Iterator模式

时间:2015-08-27 23:04:42      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:设计模式   iterator   designpattern   

STL中的集合都有Iterator,Iterator模式的作用是遍历集合中的元素。它的实现原理为把遍历封装到一个类中进行(Iterator类),这样避免了暴露这个聚合对象内部。

Iterator模式如下图:
技术分享

实现:
Aggregate.h

#ifndef AGGREGATE_H_
#define AGGREGATE_H_

typedef int Object;
class Iterator;
class Aggregate
{
public:
    Aggregate(){}
    virtual ~Aggregate(){}
    virtual Iterator* CreateIterator()=0;
    virtual Object GetItem(int idx)=0;
    virtual int GetSize()=0;
protected:

};

class ConcreteAggregate:public Aggregate
{
public:
    //enum{SIZE=3};
    static const int SIZE=3;
    ConcreteAggregate();
    ~ConcreteAggregate();
    Iterator* CreateIterator();
    Object GetItem(int idx);
    int GetSize();
private:
    Object objs_[SIZE];
};


#endif  //AGGREGATE_H_

Aggregate.cpp

#include"Aggregate.h"
#include "Iterator.h"
#include <iostream>

ConcreteAggregate::ConcreteAggregate()
{
    for (int i = 0; i < SIZE; ++i)
        objs_[i] = i;
}
ConcreteAggregate::~ConcreteAggregate()
{}
Iterator* ConcreteAggregate::CreateIterator()
{
    return new ConcreteIterator(this, 0);
}
Object ConcreteAggregate::GetItem(int idx)
{
    if (idx < GetSize())
        return objs_[idx];
    else
        return -1;
}
int ConcreteAggregate::GetSize()
{
    return SIZE;
}

Iterator.h

#ifndef ITERATOR_H_
#define ITERATOR_H_

class Aggregate;
typedef int Object;
class Iterator
{
public:
    virtual ~Iterator();
    virtual void First()=0;
    virtual void Next()=0;
    virtual bool IsDone() = 0;
    virtual Object CurrentItem() = 0;
protected:
    Iterator();
};
class ConcreteIterator :public Iterator
{
public:
    ConcreteIterator(Aggregate* ag, int idx = 0);
    ~ConcreteIterator();
    void First();
    void Next();
    bool IsDone();
    Object CurrentItem();
private:
    Aggregate* ag_;
    int idx_;
};

#endif

Iterator.cpp

#include"Aggregate.h"
#include "Iterator.h"
#include <iostream>

Iterator::Iterator()
{}
Iterator::~Iterator()
{}

ConcreteIterator::ConcreteIterator(Aggregate* ag, int idx)
{
    ag_ = ag;
    idx_ = idx;
}
ConcreteIterator::~ConcreteIterator()
{}
Object ConcreteIterator::CurrentItem()
{
    return ag_->GetItem(idx_);
}
void ConcreteIterator::First()
{
    idx_ = 0;
}
void ConcreteIterator::Next()
{
    if (idx_ < ag_->GetSize())
        ++idx_;
}
bool ConcreteIterator::IsDone()
{
    return idx_ == ag_->GetSize();
}

main.cpp

#include "Aggregate.h"
#include "Iterator.h"
#include <iostream>

int main()
{
    Aggregate* ag = new ConcreteAggregate();
    for (Iterator* it = new ConcreteIterator(ag); !it->IsDone(); it->Next())
    {
        std::cout << it->CurrentItem() << std::endl;
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

Iterator模式

标签:设计模式   iterator   designpattern   

原文地址:http://blog.csdn.net/kangroger/article/details/48034811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!