// Iterator. cpp: defines the entry point of the console application.
//
# Include "stdafx. H"
# Include <iostream>
Using namespace STD;
Typedef int data;
Class iterator;
Class Aggregate
{
Public:
Aggregate ()
{
}
Virtual ~ Aggregate ()
{
}
Virtual iterator * createiterator () = 0;
Virtual int getsize () = 0;
Virtual Data getitem (INT index) = 0;
};
Class iterator
{
Public:
Iterator ()
{}
Virtual ~ Iterator ()
{}
Virtual void first () = 0;
Virtual void next () = 0;
Virtual bool isdone () = 0;
Virtual Data currentitem () = 0;
};
Class concreteiterator: Public iterator
{
Public:
Concreteiterator (aggregate * P): m_pconcreteaggregate (P), m_index (0)
{
}
Virtual ~ Concreteiterator ()
{
}
Virtual void first ()
{
M_index = 0;
}
Virtual void next ()
{
If (m_index <m_pconcreteaggregate-> getsize ())
{
M_index ++;
}
}
Virtual bool isdone ()
{
Return m_index = m_pconcreteaggregate-> getsize ();
}
Virtual Data currentitem ()
{
Return m_pconcreteaggregate-> getitem (m_index );
}
PRIVATE:
Aggregate * m_pconcreteaggregate;
Int m_index;
};
Class concreteaggregate: Public Aggregate
{
Public:
Concreteaggregate (INT size): m_size (size)
{
M_pdata = new data [m_size];
For (INT I = 0; I <m_size; I ++)
{
M_pdata [I] = I;
}
}
Virtual ~ Concreteaggregate ()
{
Delete [] m_pdata;
M_pdata = NULL;
}
Virtual iterator * createiterator ()
{
Return new concreteiterator (this );
}
Virtual int getsize ()
{
Return m_size;
}
Virtual Data getitem (INT index)
{
If (index <m_size)
{
Return m_pdata [Index];
}
Else
{
Return-1;
}
}
PRIVATE:
Int m_size;
Data * m_pdata;
};
Int _ tmain (INT argc, _ tchar * argv [])
{
Aggregate * paggregate = new concreteaggregate (10 );
Iterator * piterator = paggregate-> createiterator ();
For (; false = piterator-> isdone (); piterator-> next ())
{
Cout <piterator-> currentitem () <Endl;
}
Return 0;
}