设计模式 - Iterator

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

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

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

class ConcreteIterator: public Iterator
{
public:
    ConcreteIterator(Aggregate* agg)
    {
        this->agg = agg;
        this->idx = 0;
    }
    ~ConcreteIterator()
    {}
    void First()
    {
        idx = 0;
    }
    void Next()
    {
        if(idx < agg->GetSize())
        {
            ++idx;
        }
    }
    bool IsDone()
    {
        return (idx == agg->GetSize());
    }
    string CurrentItem()
    {
        return agg->GetItem(idx);
    }

private:
    Aggregate* agg;
    int idx;
};

class ConcreteAggregate: public Aggregate
{
public:
    enum{SIZE = 3};
    ConcreteAggregate()
    {
        object[0] = "liang";
        object[1] = "hui";
        object[2] = "wen";
    }
    ~ConcreteAggregate()
    {}
    Iterator* CreateIterator()
    {
        return new ConcreteIterator(this);
    }
    int GetSize()
    {
        return SIZE;
    }
    string GetItem(int idx)
    {
        return object[idx];
    }

private:
    string object[SIZE];
};

 

posted @ 2013-05-06 14:16  Leung文  阅读(140)  评论(0)    收藏  举报