Iterator Mode C + + implementation 1 definition
He provides a way to access individual elements in a container object without leaking the object's internal details
Note: iterators are serviced for containers. The iterator pattern provides the convenience of traversing the container, which only manages the addition and subtraction of the elements, and it needs to pass over to the iterator as well.
2 class Diagram
Role analysis
Iterator abstract iterations, which define interfaces for accessing and traversing elements, are generally fixed interfaces: First,next,isdone/last
Concreteiterator a specific iterator that implements the iterator interface to complete the traversal of the container element
Aggregate abstract container, which is responsible for providing the interface of the specific iterator role, is bound to provide a createiterator method.
Concreteaggregate a specific container to implement an interface-defined method to create an object that accommodates an iterator
3 implementation
Class Iterator;
typedef int Object;
Class Interator;
Class Aggregate
{
Public
Virtual ~aggregate ();
Virtual iterator* createiterator () = 0;
Virtual Object GetItem (int idx) = 0;
virtual int getsize () = 0;
Protected
Aggregate ();
Private
};
Class Concreteaggregate:public Aggregate
{
Public
enum {SIZE = 3};
Concreteaggregate ();
~concreteaggregate ();
iterator* Createiterator ();
Object GetItem (int idx);
int GetSize ();
Protected
Private
Object _objs[size];
};
#include <iostream>
using namespace Std;
Aggregate::aggregate ()
{
}
Aggregate::~aggregate ()
{
}
Concreteaggregate::concreteaggregate ()
{
for (int i = 0; i < SIZE; i++)
_objs[i] = i;
}
Concreteaggregate::~concreteaggregate ()
{
}
iterator* Concreteaggregate::createiterator ()
{
return new Concreteiterator (this);
}
Object concreteaggregate::getitem (int idx)
{
if (IDX < this->getsize ())
return _OBJS[IDX];
Else
return-1;
}
int Concreteaggregate::getsize ()
{
return SIZE;
}
Class Aggregate;
typedef int Object;
Class Iterator
{
Public
Virtual ~iterator ();
virtual void First () = 0;
virtual void Next () = 0;
virtual bool IsDone () = 0;
Virtual Object currentitem () = 0;
Protected
Iterator ();
Private
};
Class Concreteiterator:public Iterator
{
Public
Concreteiterator (aggregate* ag, int idx = 0);
~concreteiterator ();
void First ();
void Next ();
BOOL IsDone ();
Object CurrentItem ();
Protected
Private
Aggregate* _ag;
int _idx;
};
Iterator::iterator ()
{
}
Iterator::~iterator ()
{
}
Concreteiterator::concreteiterator (aggregate* AG, int idx)
{
This->_ag = AG;
This->_idx = idx;
}
Concreteiterator::~concreteiterator ()
{
}
Object Concreteiterator::currentitem ()
{
Return _ag->getitem (_IDX);
}
void Concreteiterator::first ()
{
_idx = 0;
}
void Concreteiterator::next ()
{
if (_idx < _ag->getsize ())
_idx++;
}
BOOL Concreteiterator::isdone ()
{
return (_idx = = _ag->getsize ());
}
Design pattern-Iterator Mode C + + implementation