Design pattern (behavioral) iterator mode (Iterator pattern)

Source: Internet
Author: User

PS One sentence: Eventually choose Csdn to organize the publication of the knowledge points of these years, the article parallel migration to CSDN. Because CSDN also support markdown grammar, Ah!

"Craftsman Joshui Http://blog.csdn.net/yanbober" read the previous "design pattern (behavioral) observer pattern (Observer pattern)" http://blog.csdn.net/yanbober/ article/details/45484749

Overview

In the process of software building, the internal structure of the collection object is often different. But for these collection objects, we want to allow the external client code to transparently access the elements contained in it without exposing its internal structure, and this "transparent traversal" provides the possibility that the same algorithm operates on multiple collection objects. Using object-oriented techniques to abstract this traversal mechanism into an "iterator object" provides an elegant way to "respond to changing collection objects."

Core

Concept: provides a way to access an aggregated object without exposing an internal representation of the object whose alias is a cursor. An iterator pattern is an object behavior pattern.

Iterator mode structure important core modules:

Iterator Role (Iterator)

The iterator role is responsible for defining the interfaces that access and traverse elements.

Specific iterator role (concrete Iterator)

The specific iterator role is to implement the iterator interface and to record the current position in the traversal.

Container Role (Container)

The container role is responsible for providing the interface that creates the specific iterator role.

Specific container roles (concrete Container)

The specific container role implements the interface that creates the specific iterator role-the specific iterator role is related to the structure of the container.

The factory method pattern is applied in the iterator pattern, the abstract iterator corresponds to the abstract product role, and the specific iterator corresponds to the specific product role, and the abstract aggregation class corresponds to the abstract factory role, which corresponds to the specific factory role.

Usage Scenarios

Accesses the contents of an aggregated object without exposing its internal representation.

Supports multiple traversal of an aggregated object.

Provides a unified interface for traversing different aggregation structures (that is, support for polymorphic iterations).

The iterator pattern is associated with the collection, in general, as long as we implement a set, we need to provide an iterator to this collection, like Collection,list, set, map, etc. in Java, these collections have their own iterators. If we were to implement a new container like this, we would certainly need to introduce an iterator pattern to implement an iterator to our container. However, because the container is too closely related to iterators, most languages provide iterators when implementing the container, and the containers and iterators provided by those languages can meet our needs in the vast majority of cases, so it is still relatively uncommon for us to practice the scenario of the iterator pattern ourselves. We just need to use the containers and iterators that are already in the language.

Program Ape Instance

The following example is a simple iterator instance program that does not explain too much:

 PackageYanbober.github.io;ImportJava.util.ArrayList;ImportJava.util.List;//Container role (Container)Interface Container {voidAdd (Object obj);voidRemove (Object obj); Iterator createiterator ();}//Specific container role (concrete Container)Class Concretecontainer implements Container {PrivateList<object> list; Public Concretecontainer(list<object> List) { This. list = list; }@Override     Public void Add(Object obj)    {List.add (obj); }@Override     Public void Remove(Object obj)    {list.remove (obj); }@Override     PublicIteratorCreateiterator() {return NewConcreteiterator (list); }}//iterator Role (Iterator)Interface Iterator {Object first (); Object next ();BooleanHasnext (); Object CurrentItem ();}//Specific iterator role (concrete Iterator)Class Concreteiterator implements Iterator {PrivateList<object> list;Private intCursor Public Concreteiterator(list<object> List) { This. list = list; }@Override     PublicObject First() {cursor =0;returnList.get (cursor); }@Override     PublicObjectNext() {Object ret =NULL;if(Hasnext ())        {ret = list.get (cursor); } cursor++;returnRet }@Override     Public Boolean Hasnext() {return!    (Cursor = = List.size ()); }@Override     PublicObjectCurrentItem() {returnList.get (cursor); }}//Client Public  class Main {     Public Static void Main(string[] args) {List<object> List =NewArraylist<object> (); List.add ("Android"); List.add ("PHP"); List.add ("C Language"); Container Container =NewConcretecontainer (list); Container.add ("HardWare"); Iterator Iterator = Container.createiterator (); while(Iterator.hasnext ())        {System.out.println (Iterator.next ()); }    }}

L'm a Grade! To implement an iterator pattern using an inner class:

In the example above, there is a double relationship between a specific iterator class and a specific aggregation class, where one relationship is an association and a reference to a specific aggregate object needs to be maintained in the specific iterator, which is intended to access the data stored in the aggregated object so that the iterator can traverse the data. In addition to using affinity relationships, to enable iterators to access data in aggregated objects, we can also design an iterator class as an inner class of an aggregate class. The following code example is an improved version of the above code. In fact, the client code is the same regardless of the way it is used. The client does not have to care about the details of the creation of the specific iterator object, just by calling the factory method Createiterator () to get an available iterator object, which is also the benefit of using the factory method pattern, which encapsulates the object's creation process through the factory, simplifying the client's invocation.

 PackageYanbober.github.io;ImportJava.util.ArrayList;ImportJava.util.List;//Container role (Container)Interface Container {voidAdd (Object obj);voidRemove (Object obj); Iterator createiterator ();}//Specific container role (concrete Container)Class Concretecontainer implements Container {PrivateList<object> list; Public Concretecontainer(list<object> List) { This. list = list; }@Override     Public void Add(Object obj)    {List.add (obj); }@Override     Public void Remove(Object obj)    {list.remove (obj); }@Override     PublicIteratorCreateiterator() {return NewConcreteiterator (); }//Specific iterator role (concrete Iterator)Class Concreteiterator implements Iterator {Private intCursor Public Concreteiterator() {        }@Override         PublicObject First() {cursor =0;returnList.get (cursor); }@Override         PublicObjectNext() {Object ret =NULL;if(Hasnext ())            {ret = list.get (cursor); } cursor++;returnRet }@Override         Public Boolean Hasnext() {return!        (Cursor = = List.size ()); }@Override         PublicObjectCurrentItem() {returnList.get (cursor); }    }}//iterator Role (Iterator)Interface Iterator {Object first (); Object next ();BooleanHasnext (); Object CurrentItem ();}//Client Public  class Main {     Public Static void Main(string[] args) {List<object> List =NewArraylist<object> (); List.add ("Android"); List.add ("PHP"); List.add ("C Language"); Container Container =NewConcretecontainer (list); Container.add ("HardWare"); Iterator Iterator = Container.createiterator (); while(Iterator.hasnext ())        {System.out.println (Iterator.next ()); }    }}
sum up a

Advantages of the iterator pattern:

It supports traversing an aggregate object in different ways, and multiple traversal methods can be defined on the same aggregate object.

Iterators simplify the aggregation classes. Because of the introduction of iterators, it is not necessary to provide data traversal in the original aggregation object, which can simplify the design of aggregation class.

In the iterator mode, because of the introduction of the abstraction layer, it is convenient to add new aggregation classes and iterator classes without modifying the original code to meet the requirements of the "open and close principle".

Iterator Pattern Disadvantage:

Because the iterator pattern separates the responsibilities of storing data and traversing data, adding new aggregation classes requires corresponding additions to the new iterator classes, and the number of classes increases in pairs, which in some way increases the complexity of the system.

Abstract iterators are difficult to design, need to take into account the future expansion of the system, such as the JDK built-in iterator iterator can not implement reverse traversal, if you need to implement reverse traversal, only through its subclass listiterator and so on to achieve, The Listiterator iterator cannot be used to manipulate aggregate objects of the set type. When customizing iterators, it is not easy to create a fully-considered abstract iterator.

"Artisan Joshui Http://blog.csdn.net/yanbober" continues to read the "design pattern (behavioral) strategy pattern (strategy pattern)" http://blog.csdn.net/yanbober/article/ details/45498567

Design pattern (behavioral) iterator mode (Iterator pattern)

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.