迭代器模式(Iterator):提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。
使用场景:当我们需要访问一个聚集对象时,而且不管这些对象是什么都需要遍历的时候,我们可以考虑使用迭代器模式。如果我们需要对聚集有多种方式遍历时,也可以考虑使用迭代器模式。迭代器一般需要提供开始,下一个,是否结束,当前项的内容等方法。
#ifndef ITERATOR_H #define ITERATOR_H #include<iostream> #include<string> #include<deque> using namespace std; class Aggregate { friend class Iterator; public: Aggregate(){} virtual Iterator *CreateIterator()=0; }; class ConcreteAggregate :public Aggregate { friend class ConcreteIterator; deque<string> passengers; public: Iterator * CreateIterator(); int Count(); void Add(string st); string This(int index); }; void ConcreteAggregate::Add(string st) { passengers.push_back(st); } string ConcreteAggregate::This(int index) { return passengers.at(index); } int ConcreteAggregate::Count() { return passengers.size(); } class Iterator { public: Iterator(){} virtual string First() = 0; virtual string Next() = 0; virtual bool IsDone() = 0; virtual string CurrentItem() = 0; }; class ConcreteIterator :public Iterator { friend class ConcreteAggregate; ConcreteAggregate aggregate; int current = 0; public: ConcreteIterator(ConcreteAggregate ); string First(); string Next(); bool IsDone(); string CurrentItem(); }; ConcreteIterator::ConcreteIterator(ConcreteAggregate ar) :aggregate(ar), current(ar.passengers.size()-1) {} std::string ConcreteIterator::First() { return aggregate.This(0); } std::string ConcreteIterator::Next() { string temp; --current; if (current>=0) temp = aggregate.This(current); return temp; } bool ConcreteIterator::IsDone() { return current >=0 ? false : true; } std::string ConcreteIterator::CurrentItem() { return aggregate.This(current); } Iterator * ConcreteAggregate::CreateIterator() { return (new ConcreteIterator(*this)); } #endif
#include"Iterator.h" int main() { ConcreteAggregate pa; pa.Add("大鸟"); pa.Add("小菜"); pa.Add("行李"); pa.Add("老外"); pa.Add("公交内部员工"); pa.Add("小偷"); ConcreteIterator Itr(pa); string temp = Itr.First(); while (!Itr.IsDone()) { cout << Itr.CurrentItem() << " 请买票。\n"; Itr.Next(); } return 0; }
时间: 2024-10-13 02:22:30