设计模式之 迭代器模式

 

class Book
{
public:
    Book(void);
    ~Book(void);
public:
    string name_;
    string Tag_;
};

class BookList
{
public:
    BookList(void);
    ~BookList(void);
public:
    void addBook(const Book *pBook){ bookList_.push_back(pBook); }
    void delBook(const Book *pBook){}
    IIterator* createIterator(void){ return new Iterator(this, bookList_.size()); }
    Book* operator[](int index){ return bookList_[index]; }

public:
    vector<Book*> bookList_;
};

template<class ItemT, class ValueTypeT>
class IIterator
{
public:
    virtual ~IIterator(void){}
    virtual void first(void) = 0;
    virtual void next(void) = 0;
    virtual ValueTypeT* currentItem(void) = 0;
    virtual bool isDone(void) = 0;
};

template <class ItemT, class ValueTypeT>
class ListIterator: public IIterator<ItemT, ValueTypeT>
{
public:
    ListIterator(const ItemT *pItem, int size): pItem_(pItem),size_(size),cur_(0){}
    ~ListIterator(void){}
public:
    virtual void first(void){ cur_ = 0; }
    virtual void next(void){ ++cur_; }
    virtual ValueTypeT* currentItem(void){ return cur_ < size_ ? pItem[cur_] : NULL; }
    virtual bool isDone(void){ return cur_ >= size_ ? true : false; }

private:
    ItemT *pItem_;
    int size_;
    int cur_;
};

 

posted on 2015-07-30 17:56  霏霏暮雨  阅读(128)  评论(0编辑  收藏  举报

导航