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