This design pattern is very simple, and we often need to call iterator when writing programs, both C ++ and Java.
So I feel nothing special. I just need to imitate the functions of the C ++ or Java iterator class.
Here is a simple example. C ++ is used to simulate some Java iterator functions.
First, we have a collection class, which contains other classes. When we need to traverse the classes contained in this collection class, we should use the iterator function.
For example, there is an original class:
class SalesPerson{private:string name;string division;public:explicit SalesPerson(string n = "", string d = "") : name(n), division(d) {}string getName(){return name;}void print(){printf("SalesPerson %s is in %s department.\n", name.c_str(), division.c_str());}};
Then, the collection class contains the above class:
class Division{private:string name;SalesPerson **sales;int number;DivisionIterator *dit;int Len;public:Division(string n) : name(n), Len(100), number(0), dit(NULL){sales = new SalesPerson*[Len];for (int i = 0; i < Len; i++){sales[i] = NULL;}}~Division(){for (int i = 0; i <= number; i++){delete sales[i];}if (sales) delete [] sales;if (dit) delete dit;}string getName(){return name;}void add(string n){sales[number++] = new SalesPerson(n, name);}DivisionIterator *iterator(){if (!dit) dit = new DivisionIterator(sales);return dit;}};
The above iterator function returns the DivisionIterator class, which is convenient for traversing the classes in this collection class.
Class DivisionIterator {private: SalesPerson ** sales; int location; int Len; public: DivisionIterator (SalesPerson ** v): sales (v), location (0), Len (100) {} SalesPerson * next () {return sales [location ++];} bool hasNext () {if (location <Len & sales [location]) return true; return false;} void remove () // temporary time-space function {}};
Finally, test its traversal function:
void salesIteratorTest(){Division divs("SalesDep");divs.add("Sally");divs.add("Jelly");divs.add("Lily");divs.add("Billy");divs.add("Cherry");DivisionIterator *it = divs.iterator();while (it->hasNext()) {SalesPerson *sa = it->next();sa->print();}}
Result:
There is no problem with the traversal function. This design mode is successfully applied and is very simple.
But the most depressing thing is not this design mode, but the Flyweight design mode. It seems that a simple function also comes down to a design mode. Maybe what I learned is not very thorough.
In general, the design pattern is still very useful. Currently, we are using the design pattern to write the framework and writing it out to show. Or an open-source project.