Design Pattern --- Iterator
template <typename T> class Iterator { public: // Interface virtual void First() = 0; virtual void Next() = 0; virtual bool IsDone() const = 0; virtual T CurrentItem() const = 0; }; template <typename T> class DequeIterator : public Iterator<T> { // data. const deque<T> &m_deque; unsigned m_curPos; public: DequeIterator(const deque<T> &d) : m_deque(d), m_curPos(0) {} public: // Interface virtual void First() override { m_curPos = 0; } virtual void Next() override { ++m_curPos; } virtual bool IsDone() const override { return m_curPos == m_deque.size(); } virtual T CurrentItem() const override { return m_deque[m_curPos]; } }; template <typename T> class DequeReverseIterator : public Iterator<T> { // data. const deque<T> &m_deque; unsigned m_curPos; public: DequeReverseIterator(const deque<T> &d) : m_deque(d), m_curPos(d.size()-1) {} public: // Interface virtual void First() override { m_curPos = m_deque.size()-1; } virtual void Next() override { --m_curPos; } virtual bool IsDone() const override { return m_curPos == -1; } // Magic and ugly. virtual T CurrentItem() const override { return m_deque[m_curPos]; } }; int main() { deque<int> d; for (int i = 0; i < 10; ++i) { d.push_back(i); } // Forward iterator. for (DequeIterator<int> i(d); !i.IsDone(); i.Next()) { cout <<i.CurrentItem() <<endl; } cout <<endl; // Backward iterator. for (DequeReverseIterator<int> i(d); !i.IsDone(); i.Next()) { cout <<i.CurrentItem() <<endl; } return 0; }
迭代器最大的优点在于将遍历的方法封装到单独的类中, 即 Iterator 类.
纵观设计模式, 还是强调把易变性封装到单独的类中.