Iterator mode (Iterator): Provides a way to sequentially access individual elements in an aggregated object without exposing the object's internal representation.
Usage scenarios: When we need to access a clustered object, and regardless of what these objects need to traverse, we can consider using the iterator pattern. You might also consider using an iterator pattern if we need to traverse the aggregation in multiple ways. Iterators generally need to provide methods such as start, next, whether to end, the contents of the current item, and so on.
#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:p ublic aggregate{friend class concreteiterator;deque<string> Passengers;public:i Terator * 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 s Tring CurrentItem () = 0;}; Class Concreteiterator:p ublic 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 ("Big Bird");p A. Add ("Side dish");p A. ADD ("luggage");p A. ADD ("foreigner");p A. ADD ("Internal transit staff");p A. ADD ("thief"); Concreteiterator ITR (PA); string temp = Itr.first (); while (! Itr.isdone ()) {cout << itr.currentitem () << "please buy a ticket. \ n "; Itr. Next ();} return 0;}
Design pattern C + + implementation 16: Iterator mode