Design Mode (iterator mode)-behavior mode

Source: Internet
Author: User

Behavior mode

Overview:

Iterator: provides a method to sequentially aggregate elements of an object without exposing the internal representation of the object.

Practical scenarios:

1. Access the content of an aggregate object without exposing its internal representation.

2. Supports multiple traversal of aggregate objects.

3. provides a unified interface (that is, multi-state iteration) for Traversing different aggregation structures ).

Class diagram:

Sample Code structure:

1. iterator abstract class

/// <Summary> /// iterator abstract class /// used to define the starting object, next object, whether to end, current object method, unified interface // </Summary> abstract class iterator {public abstract object first (); public abstract object next (); public abstract bool isdone (); public abstract object currentitem ();}

2. Implementation iterator class

Class concreteiterator: iterator {// <summary> // defines a specific aggregation object /// </Summary> private concreteaggregate aggregate; private int current = 0; /// <summary> /// the initialization object passes in the specific clustering class /// </Summary> /// <Param name = "aggregate"> </param> Public concreteiterator (concreteaggregate aggregate) {This. aggregate = aggregate;} // <summary> // The first object /// </Summary> /// <returns> </returns> Public override object first () {Return aggregate [0];} /// <summary> /// obtain the next object to be aggregated /// </Summary> /// <returns> </returns> Public override object next () {object ret = NULL; current ++; If (current <aggregate. count) {ret = aggregate [current];} return ret ;} /// <summary> /// whether the end is reached /// </Summary> /// <returns> </returns> Public override bool isdone () {Return Current> = aggregate. count? True: false ;} /// <summary> /// return the current aggregation object /// </Summary> /// <returns> </returns> Public override object currentitem () {return aggregate [current];}

3. Aggregate abstract classes

/// <Summary> /// aggregation abstract class /// </Summary> abstract class aggregate {/// <summary> /// create iterator /// </Summary >/// <returns> </returns> public abstract iterator createiterator ();}

4. Aggregation implementation class

Class concreteaggregate: aggregate {private ilist <Object> items = new list <Object> (); Public override iterator createiterator () {return New concreteiterator (this );} /// <summary> /// returns the total number of aggregates /// </Summary> Public int count {get {return items. count ;}} /// <summary> /// declare an index /// </Summary> /// <Param name = "Index"> </param> /// <returns> </returns> Public object this [int Index] {get {return items [Index];} set {items. insert (index, value );}}}

5. Client implementation

Static void testiterator () {// concreteaggregate A = new concreteaggregate (); A [0] = "Zhang San"; A [1] = "Li Si "; A [2] = "ye peng"; // declare the iterator object I =. createiterator (); object item = I. first (); While (! I. isdone () {console. writeline ("{0} go home for dinner", I. currentitem (); I. Next () ;}console. Read ();}

I. Sample 1

Generally, Starcraft jobs have the following settings: Computer farmers do not mine at first. If the battle starts, or players create the first troops, computer farmers start mining.

We will naturally think of putting computer farmers into an array, and then once the players make troops or the battle starts, we will loop through this array to let the farmers mine in it.

However, the problem arises, because the settings of each task are different, we always hope that the task development is more convenient and easy to modify (once a bug is found ).

What's more, some tasks are not for farmers to mine, but for computers to Attack Players.

So much fixed details (stored in arrays) and dependency details (for Array loops) will make the code highly correlated.

The problem to be solved: abstracting the transactions processed cyclically.

Idea: the key is the loop of farmers. Array Processing is just a way. We consider abstract arrays instead of specific arrays.

Iterator mode example:

<? PHP // aggregation interface, which means that all computer farmers gather in this class and interface iaggregate {// implement the specific aggregation class, obtain the public function createiterator ();} // The aggregate class concreteaggregate implements iaggregate {public $ workers; // stores the farmer's array, note that you do not need to use Arrays for processing. After reading all the code, you will know the public function createiterator () {// method for obtaining the iterator return New concreteiterator ($ this );} public Function addelement ($ element) {// Method for adding elements. Here the elements are farmers $ this-> workers [] = $ element;} public funct Ion getat ($ index) {// return $ this-> workers [$ Index];} public function getlength () {// return count ($ this-> Workers);} // The iterator interface. Note that PhP5 has a built-in interface called iterator, so here we change to iiteratorinterface iiterator {public function hasnext (); // whether the element loop is complete public function next (); // return the next element, add the pointer to 1} // The specific iterator class concreteiterator implements iiterator {public $ collection; // public $ index of the set to be iterated; // the pointer to Public Function _ Construct (iaggregate $ collection) {// constructor, determines the set of iterations, and sets the pointer to zero $ this-> collection = $ collection; $ this-> Index = 0;} public function hasnext () {// whether the element has been cyclically completed if ($ this-> index <$ this-> collection-> getlength ()) {return true;} return false;} public function next () {// return the next element, add 1 $ element = $ this-> collection-> getat ($ this-> index); $ this-> index ++; return $ element ;}} to the pointer ;}} // initialize the computer farmer's aggregation object $ farmeraggregate = new C Oncreteaggregate (); // Add a farmer. Here, a string is used to represent $ farmeraggregate-> addelement ("svc1"); $ farmeraggregate-> addelement ("svc2 "); // get iterator $ iterator = $ farmeraggregate-> createiterator (); // loop the farmer's clustered object while ($ iterator-> hasnext ()) {$ element = $ iterator-> next (); // obtain the echo $ element of the next farmer; // simple output}?>

Purpose Summary: The iterator mode creates an array-like form. From the code above, we can see that if you want to modify the processing of the loop or modify the set of loops, you do not need to modify other related code.

Implementation Summary: a class for managing aggregation is required, such as the concreteaggregate above. In addition, the iterator class is required, such as the concreteiterator above. Then, all the operations, such as adding elements, getting the next element, pointer and other Array Operations, are abstracted, so that other codes only need to use methods, such as getlength (), instead of the segmented count () function, you do not need to change the code other than the clustering class even if you do not need to store Arrays for farmers.

Ii. Sample 2

The iterator mode is a behavior mode. Its intent is to provide a method to access each element in an aggregate object sequentially without exposing the internal representation of the object. An aggregate object, such as a list, should provide a way for others to access its elements. However, you do not need to expose its internal structure. In addition, you may need to traverse the list in the following ways to meet different requirements. However, even if you can predict the traversal operations required, you may not want the list interface to be filled with different traversal operations. You may also need to traverse the same list at the same time. The iterator mode helps you solve all these problems. The key idea of this mode is to separate the access and traversal of the list from the list object and put it into an iterator object, the iterator class defines an interface for accessing the list element. The iterator object is responsible for tracking the current element, that is, it knows that those elements have already been traversed. Before instantiating the list iterator, you must provide the list to be traversed. Once you have an instance of the List iterator, you can access each element of the list in sequence. The currentitem operation returns the current element in the list. The first operation initializes the iterator so that the current element points to the first element in the list. Next operation pushes the current element Pointer Forward to the next element, isdone checks whether the last element has been crossed, that is, the traversal is completed.

For example, a common TV can define a remote control. a TV set produced in each factory has a remote control. This is a bit like an abstract factory model, but it is not an abstract factory model, the focus is on the iterator mode. The TV channel is item. Each remote control has a traversal function to traverse all channels. As shown in, Applicability: l
Access the content of an aggregate object without exposing its internal representation. L
Supports multiple traversal of sentences and objects. L
Provides a unified interface for Traversing different aggregation structures.

Participant: iterator defines the interface for accessing and traversing elements. Concreteiterator (Controller): The specific iterator implements the iterator interface to track the current position for the aggregation time. Aggregate (televation): Aggregation defines the interface for creating the corresponding iterator object. Concreteaggregate (haiertv): The specific aggregation implementation creates the corresponding iterator interface. This operation returns an appropriate instance of concreteiterator. Collaboration relationship: concreteiterator tracks the current object in the aggregation and can calculate the next object to be traversed. Advantages of using the iterator: 1. It supports traversing an aggregation in different ways. Complex aggregation can be traversed in multiple ways. 2. The iterator simplifies the aggregation interface. With the iterator's traversal interface, the aggregation itself does not need a similar traversal interface, which simplifies the aggregation interface. 3. On the same aggregation, You can have multiple traversal nodes to maintain the traversal status of each iterator. Therefore, you can perform multiple traversal at the same time. In this example, television defines an interface to return the list of channels. This is actually a factory method, but only the type of the produced product supports iterator operations. The specific code is as follows:
Iterator interface: Package iterator; public interface iterator {public item first (); Public item next (); Public Boolean isdone (); Public item currentitem ();} the Controller class implements the iterator interface. Package iterator; import Java. util. vector; public class controller implements iterator {private int current = 0; vector channel; Public controller (vector v) {channel = V;} public item first () {current = 0; return (item) channel. get (current);} public item next () {current ++; Return (item) channel. get (current);} public item currentitem () {return (item) channel. get (current);} public Boolean isdone () {re Turn current> = channel. size ()-1 ;}} television interface: Package iterator; import Java. util. vector; public interface television {public iterator createiterator (); Public vector getchannel ();} haiertv class implements the television interface. Package iterator; import Java. util. vector; public class haiertv implements television {private vector channel; Public haiertv () {channel = new vector (); channel. addelement (new item ("Channel 1"); channel. addelement (new item ("Channel 2"); channel. addelement (new item ("Channel 3"); channel. addelement (new item ("Channel 4"); channel. addelement (new item ("Channel 5"); channel. addelement (new item ("channe L 6 "); channel. addelement (new item ("Channel 7");} public vector getchannel () {return channel;} public iterator createiterator () {return new controller (Channel );}} client client: Package iterator; public class client {public static void main (string [] ARGs) {Television TV = new haiertv (); iterator it = TV. createiterator (); system. out. println (it. first (). getname (); While (! It. isdone () {system. out. println (it. next (). getname () ;}} interface of the item class: Package iterator; public class item {private string name; Public item (string aname) {name = aname ;} public String getname () {return name ;}}

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.