Mode motive
An aggregate object, such as a list or a collection (set), should provide a way for others to access its elements without exposing its internal structure.
For different needs, it is possible to traverse the entire aggregation object in different ways, but we do not want to be flooded with different traversal operations in the abstract layer interface of the aggregation object.
How to traverse an aggregation object without needing to understand the internal structure of the aggregation object, but also to provide many different ways of traversal, this is the problem that the iterator pattern solves.
In the iterator pattern, an external iterator is provided to access and traverse the aggregated object, which defines an interface to access the aggregation element, and can track the currently traversed elements to see which elements have been traversed and which are not.
With the iterator pattern, we will find that the operation of a complex aggregate object becomes so simple.
Pattern definition
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.
Iterator Pattern:provide A by access the elements of an aggregate object sequentially without exposing its underlying Representation.
Frequency of Use:high
UML diagram
Pattern structure
The iterator pattern contains the following roles:
Iterator: Abstract iterator
Concreteiterator: Specific iterators
Aggregate: Abstract Aggregation class
Concreteaggregate: Specific aggregation classes
Pattern Analysis
Aggregation is a data structure that manages and organizes data objects.
Aggregation objects have two responsibilities: one is to store internal data, and the other is to traverse internal data.
Storing data is the most basic responsibility of aggregating objects.
Extracts the behavior of the data in the aggregated object, encapsulates it into an iterator, and iterates through the internal data of the aggregated object through a specialized iterator, which is the essence of the iterator pattern. The iterator pattern is the perfect embodiment of the "single responsibility Principle".
The factory method pattern is applied in the iterator pattern, the aggregation class acts as a factory class, and the iterator acts as a product class, and because the abstraction layer is defined, the system is very extensible, and the client can program for abstract aggregate classes and abstract iterators.
Since the class libraries of many programming languages have already implemented the iterator pattern, we seldom customize iterators in practice, simply by using the defined iterators in Java, C # and other languages, and iterators have become one of the basic tools we use to manipulate aggregated objects.
Pattern Instances and parsing
Want to go? OK! Buy tickets first-iterator pattern example
System structure
Iterator: Abstract iterator
namespaceiteratorpattern{//Iterator iterator abstract class Abstract classIterator {//used to define the start object, get the next object,//determine whether to end, current object, etc. abstract methods, unified interface Public Abstract ObjectFirst (); Public Abstract ObjectNext (); Public Abstract BOOLIsDone (); Public Abstract ObjectCurrentItem (); }}
Concreteiterator: Specific iterators
usingSystem;namespaceiteratorpattern{//concreteiterator Specific iterator classes, inheriting iterator classConcreteiterator:iterator {//define a specific clustered object Privateconcreteaggregate Aggregate; Private intCurrent =0; //when initializing, the specific clustered object is passed in PublicConcreteiterator (concreteaggregate aggregate) { This. aggregate =aggregate; } Public Override ObjectFirst () {returnaggregate[0]; } Public Override ObjectNext () {Object ret=NULL; Current++; if(Current <aggregate. Count) {ret=Aggregate[current]; } returnret; } Public Override BOOLIsDone () {returnCurrent >= aggregate. Count?true:false; } Public Override ObjectCurrentItem () {returnAggregate[current];//returns the current clustered object } }}
Aggregate: Abstract Aggregation class
namespace iteratorpattern{ //aggregate Aggregate abstract class Aggregate { // Create iterator public abstract Iterator createiterator (); }}
Concreteaggregate: Specific aggregation classes
usingSystem;usingSystem.Collections.Generic;namespaceiteratorpattern{//concreteaggregate Specific aggregation class inheritance aggregate classConcreteaggregate:aggregate {//declares an IList generic variable, which is used to hold the aggregate object, and can be implemented with ArrayList Privateilist<Object> items =NewList<object>(); Public OverrideIterator Createiterator () {return NewConcreteiterator ( This); } Public intCount {Get{returnItems. Count; }//returns the total number of aggregates } //declaring an indexer Public Object This[intIndex] { Get{returnItems[index];} Set{items. Insert (index, value); } } }}
Client: Customer Class
usingSystem;namespaceiteratorpattern{classProgram {Static voidMain (string[] args) {Concreteaggregate a=Newconcreteaggregate (); a[0] ="Zhang San"; a[1] ="John Doe"; a[2] ="Harry"; Iterator I=NewConcreteiterator (a); Objectitem =I.first (); while(!I.isdone ()) {Console.WriteLine ("{0} please buy a ticket! ", I.currentitem ()); I.next ();//Next passenger} console.read (); } }}
Model Pros and cons
Advantages of the iterator pattern
? It supports traversing an aggregate object in a different way.
The iterator simplifies the aggregation class.
? You can have more than one traversal on the same aggregation.
? In the iterator mode, 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".
Disadvantages of the iterator pattern
? 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.
Mode applicable environment
The iterator pattern can be used in the following situations:
? Access the contents of an aggregated object without exposing its internal representation.
? You need to provide multiple traversal methods for the aggregation object.
? Provides a unified interface for traversing different aggregation structures.
"Statement and thanks"
This article, on the shoulders of many giants, draws on and cites many other works or writings that others have copyrighted, and is here to thank the former people for their contributions. And at the same time publish the quoted content, the original author or source (some of the content from the Internet can not be traced to the source, deeply regret).
"References"
Design mode-the basis of reusable object-oriented software author: [US] Erich gamma/richard Helm/ralph johnson/john vlissides Translator: Li Yingjun/Ma Xiaoxing/Cai Min/Liu Jianzhong and other machinery industry press
Refactoring-Improving the design of existing code author: Martin Fowler Translator: China Power Press, HOU-jie
"Agile software Development-principles, patterns and practices" Author: Robert C. Martin Tsinghua University Press
"Programmer's path to cultivation-from small to expert" by Andrew hunt/david Thomas Electronics Press
Head First design mode author: Freeman translator: O ' Reilly Taiwan company China Power Press
"Zen of Design Pattern" Author: Qin Xiaobo Machinery Industry Press
MSDN Webcast "C # Object-oriented design mode discussion on" lecturer: Li Jianzhong
Liu wei. design mode. Beijing: Tsinghua University Press, 2011.
Liu wei. Design pattern Training Tutorial. Beijing: Tsinghua University Press, 2012.
"Big Liar design Mode" Author: Geoscience Tsinghua University Press
C # Illustrated Tutorial Author: Solis Translator: Surin/Zhu Ye People's post and telecommunications press
"You must know. NET" Author: Wang Tao
. NET in Project author: Li Tianping Electronics Press
The Microsoft. NET Enterprise Application Architecture Design Author: (US) Esposito and other translators: Chen Lifu
http://www.dofactory.com/Patterns/Patterns.aspx. NET Design Patterns
Http://www.cnblogs.com/zhenyulu Blog Lu Zhenyu
Http://www.cnblogs.com/terrylee Blog Li Huijun
http://www.cnblogs.com/anlyren/Blog Anlyren
Http://www.cnblogs.com/idior Blog Idior
Http://www.cnblogs.com/allenlooplee blog Allen Lee
HTTP://BLOG.CSDN.NET/AI92 Blog ai92
http://www.cnblogs.com/umlonline/Blog Zhang
http://www.cnblogs.com/lovecherry/Blog Lovecherry
In-depth design pattern-iterator mode (Iterator pattern)