Design pattern Learning Notes-iterator mode

Source: Internet
Author: User

I. INTRODUCTION
Today, learning about the iterator pattern in design mode, the iterator pattern is a very, very common design pattern, so useful, c#,java it as a built-in implementation, C + + also provides STL iterators, which we use every day, but instead feel that the iterator mode is not so important. After all, our own implementation of the iterator is still less than the implementation of native language, but in order to learn, we still need to look at the implementation of the iterator pattern, only to understand the principle, to better use.Most of the time we are dealing with a group of objects, relative, we need to manage the container class to store the object. We need methods such as add,remove, but we also need a way to access the objects within the container. For example, get the first object, end object, next object next, and so on. If we implement these methods in a container, the responsibilities of the containers are too heavy and the iterations are different, for example, if we need to iterate backwards from the front or backward, we can change the iterators directly to achieve different effects. By extracting the contents of the iteration, we can get more flexible object access forms.Let's look at the definition of the iterator pattern and the UML class diagram:Iterator pattern (Iterator pattern): Provides a way to access an aggregated object without exposing the object's internal representation, which is aliased to a cursor. An iterator pattern is an object behavior pattern.

Analyzing the UML diagram, our container class is equivalent to aggregate, providing some abstract container methods, the abstract iterator class defines some iterative methods, such as getting the end-to-end element, the next element, the current element, and so on, but the concrete iterative way is implemented by Concreteiterator. The container class Concreteaggregate class as the iterator factory, you can create a corresponding iterator for this container.
Two. Examples of iterator patterns let's look directly at an example of an iterator pattern:
Design Pattern.cpp:Defines The entry point for the console application.//#include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <map>using namespace std;//iterator base class iterator{public:/ /iterator pointing backward to a virtual void Next () = 0;//iterator to the first element of virtual void Begin () = 0;//iterator to the end of the container virtual bool Isend () = 0;//Returns the element VI referred to by the current iterator Rtual string getcurrent () = 0;};/ /container base class vecterbase{public://add element virtual void Add (string elem) = 0;//Get current element virtual string get (int index) = 0;//Get container current capacity virtual int Count () = 0;//iterator factory virtual iterator* createiterator () = 0;};/ /Specific iterator classes class Concreteiterator:public Iterator{private:int M_currentindex; vecterbase* m_vec;public:concreteiterator (vecterbase* vec): M_vec (VEC), M_currentindex (0) {}virtual void Next () override{m_currentindex++;} virtual void Begin () {m_currentindex = 0;} virtual bool Isend () {return m_currentindex >= m_vec->count ();} Virtual String GetCurrent () {return m_vec->get (m_currentindex);}};/ /Specific Container class ConcretevectOr:public vecterbase{private:vector<string> stringvec;public:void Add (string elem) {Stringvec.push_back (elem) ;} string Get (int index) {return stringvec[index];} int Count () {return stringvec.size ();} iterator* Createiterator () {return new concreteiterator (this);}}; int _tmain (int argc, tchar* argv[]) {vecterbase* VEC = new Concretevector (); Vec->add ("Zhang San"); Vec->add ("John Doe"); vec- >add ("King of the two Leper"); iterator* it = Vec->createiterator (); for (It->begin ();!it->isend (); It->next ()) {cout << it->getcurrent () << Endl;} Does it look like an iterator inside a STL? /*for (Std::vector<string>::iterator it = Vec.begin (); It! = Vec.end (); ++it) {cout << (*it) << Endl;} */system ("pause"); return 0;}
Results: Zhang San
John doe
Wang er Leper
Please press any key to continue ...
Let's take a quick look at the iterator, and here I write a sample of the STL iterator code as a comparison, and our iterator usage is basically the same as the STL. First, an iterator is created, the initial value is the position of the first element of the container, and then iterated until the tail element is reached. Each iteration moves backwards by one element.

Three. Summary of the iterator pattern
Finally, let's look at the pros, cons, and timing of the iterator pattern: Pros: 1 The iterator simplifies the container class and implements a single responsibility principle. Separating traversal and storage functionality, whether new container types or new iterators, conforms to the open-close principle. 2) can provide a variety of iterations, such as a new iteration from the forward iteration and so on.
Cons: 1 The design of the iterator is difficult, it is difficult to abstract a relatively complete set of iterator base class. 2) Iterators make the number of system classes increase, to some extent difficult to understand.
Use time: 1) Access the contents of an aggregated object without exposing its internal representation. Separating the access of the aggregated object from the storage of the internal data makes it unnecessary to understand the internal implementation details of the aggregated object.
2) You need to provide multiple traversal methods for an aggregated object.
3) provides a unified interface for traversing different aggregation structures, providing different traversal modes for different aggregation structures in the implementation class of the interface, and the client can manipulate the interface consistently.

Finally, incidentally, the iterator pattern is so useful that either the language or the base library provides a complete iterator implementation, but this pattern is not very meaningful to us ....

Design pattern Learning Notes-iterator mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.