Design Patterns 15-design patterns iterator (behavior type)

Source: Internet
Author: User
1. Scenario Simulation

A company acquires another company and now needs to integrate the wage data between the two companies. However, two companies use linked lists for storage and arrays for storage, but the wage data model is similar.
The preceding problems can be abstracted as: how to access different aggregate objects in a unified manner.
2. Use the iterator mode to solve the 2.1 iterator Definition

Provides a method to access each element in an aggregate object sequentially without exposing the internal representation of the object.
2.2 structure of the iterator

 
2.3 sample iterator code

Package demo13.iterator. example1;/*** iterator interface, define operations to access and traverse elements */public interface iterator {/*** move to the first position of the aggregation object */Public void first (); /*** move to the next position of the aggregation object */Public void next (); /*** determine whether the last position of the aggregated object has been moved * @ return true indicates that the object has been moved to the last position of the aggregated object, * false indicates that the object has not been moved to the last position of the aggregate object */Public Boolean isdone (); /*** get the current element of the iteration * @ Return Current element of the iteration */public object currentitem ();} **************************************** ************* * ***************** Package demo13.iterator. example1;/*** specific iterator implementation object, it indicates that the aggregate object is an array iterator * different aggregate objects correspond to different iterators */public class concreteiterator implements iterator {/*** holding the specific Iteration */private concreteaggregate aggregate; /*** internal index, which records the index location from the current iteration. *-1 indicates that at the beginning, the iterator points to */private int Index =-1 before the first object of the aggregate object;/*** constructor, pass in the specific aggregation object to be iterated * @ Param aggregate the specific aggregation object to be iterated */Public concreteiterator (concreteaggregate aggregate) {This. aggregate = aggregate;} public void first () {Index = 0;} public void next () {If (index <this. aggregate. size () {Index = index + 1 ;}} public Boolean isdone () {If (Index = This. aggregate. size () {return true;} return false;} public object C Urrentitem () {return this. aggregate. get (INDEX );}} **************************************** * ***************************** package demo13.iterator. example1;/*** interface for aggregating objects, define the interface for creating the corresponding iterator object */public abstract class aggregate {/*** factory method, create the corresponding iterator object interface * @ return interface of the corresponding iterator object */public abstract iterator createiterator ();} **************************************** * **************************** package demo13.iterator. Example1;/*** specific aggregate object to create the corresponding iterator object function */public class concreteaggregate extends aggregate, indicates the specific content of the aggregate object */private string [] Ss = NULL;/*** constructor, pass in the specific content of the aggregate object * @ Param SS aggregate object specific content */Public concreteaggregate (string [] ss) {This. ss = SS;} public iterator createiterator () {// implement the factory method of creating iterator return New concreteiterator (this );} /*** retrieve the element corresponding to the Index * @ Param Index * @ return the element corresponding to the Index */public object get (INT index) {object retobj = NULL; If (index <ss. length) {retobj = ss [Index];} return retobj;}/*** get the size of the aggregate object * @ return the size of the aggregate object */Public int size () {return this. SS. length ;}} **************************************** * **************************** package demo13.iterator. example1; public class client {/*** method, using the iterator function. * The iterator is used to iterate and aggregate objects */Public void someoperation () {string [] names = {"Zhang San", "Li Si", "Wang Wu "}; // create an aggregate object aggregate = new concreteaggregate (names); // cyclically output the iterator it = aggregate. createiterator (); // first set the iterator to the first element it. first (); While (! It. isdone () {// retrieve the current element to object OBJ = it. currentitem (); system. out. println ("the OBJ =" + OBJ); // If the iteration has not reached the end, it will be iterated down. next () ;}} public static void main (string [] ARGs) {// you can test Client client = new client (); client. someoperation ();}}
3. Do not use the iterator to implement the instance (Scenario Simulation) Code

The code is very simple, and the comments are very clear, so I won't go into details one by one.

Package demo13.iterator. example2;/***** wage description model object */public class paymodel {/***** wage payer */private string username; /*** payment amount */private double pay; Public String GetUserName () {return username;} public void setusername (string username) {This. username = username;} public double getpay () {return pay;} public void setpay (double pay) {This. pay = pay;} Public String tostring () {return "username =" + username + ", pay =" + pay ;}} **************************************** * *********************** package demo13.iterator. example2; import Java. util. *;/*** existing salary management object of the customer */public class paymanager {/*** aggregation object, here is the Java Collection object */private list = new arraylist ();/*** get the salary list * @ return salary list */public list getpaylist () {return list;}/*** calculate the salary. In fact, there should be many parameters. To demonstrate how to calculate the salary from simple */Public void calcpay, and fill in the salary information in the salary list // for testing, do some false data into the paymodel PM1 = new paymodel (); pm1.setpay (3800); pm1.setusername ("James "); paymodel PM2 = new paymodel (); pm2.setpay (5800); pm2.setusername (""); list. add (PM1); list. add (PM2 );}} **************************************** * **************************** package demo13.iterator. example2;/*** salary management class of the company acquired by the customer */public class salarymanager {/*** use Arrays for management */private paymodel [] PMS = NULL; /*** get the salary list ** @ return salary list */Public paymodel [] getpays () {return PMS;}/*** calculate the salary. In fact, there should be many parameters, to demonstrate how to calculate the salary from simple */Public void calcsalary () {// and fill the salary information in the salary list. // to test, do some false data into paymodel PM1 = new paymodel (); pm1.setpay (2200); pm1.setusername ("Wang Wu"); paymodel PM2 = new paymodel (); pm2.setpay (3600 ); pm2.setusername ("Zhao "); PMS = new paymodel [2]; PMS [0] = PM1; PMS [1] = PM2 ;}} **************************************** **************************************** * ************** package demo13.iterator. example2; import Java. util. *; public class client {public static void main (string [] ARGs) {// access the group's salary list paymanager = new paymanager (); // obtain the paymanager after calculation. calcpay (); Collection paylist = paymanager. getpaylist (); iterator it = paylist. iterator (); system. out. println ("group payroll:"); While (it. hasnext () {paymodel PM = (paymodel) it. next (); system. out. println (PM);} // access the salary list of the newly acquired company salarymanager = new salarymanager (); // calculate and obtain salarymanager. calcsalary (); paymodel [] PMS = salarymanager. getpays (); system. out. println ("new company payroll:"); For (INT I = 0; I <PMS. length; I ++) {system. out. println (PMS [I]) ;}}
4. Use the iterator mode to implement the scenario Mode

Through the code just now, we can clearly find that the structure used by the client is different. One is an array and the other is a collection, so that we can understand the internal manifestation of the client. Can we change the iterator mode to the following?

Public class client {public static void main (string [] ARGs) {// access the group's salary list paymanager = new paymanager (); // obtain the paymanager after calculation. calcpay (); system. out. println ("group payroll:"); test (paymanager. createiterator (); // access the salary list of the newly acquired company salarymanager = new salarymanager (); // calculate and then obtain salarymanager. calcsalary (); system. out. println ("list of newly acquired company salaries:"); test (salarymanager. createiterator ();}/*** test whether the aggregate object iterator can be accessed * @ Param it */Private Static void test (iterator it) {// cyclically output the value in the aggregate object // first set the iterator to the first element it. first (); While (! It. isdone () {// retrieve the current element to object OBJ = it. currentitem (); system. out. println ("the OBJ =" + OBJ); // If the iteration has not reached the end, it will be iterated down. next ();}}}

In this way, the client is quite comfortable to use, and the answer is yes. Next we will unify the access aggregation interface.
The Code is as follows:
4.1 The easiest way to allow clients to perform unified access is to define a unified interface for them.

Package demo13.iterator. example3;/*** iterator interface, define operations to access and traverse elements */public interface iterator {/*** move to the first position of the aggregation object */Public void first (); /*** move to the next position of the aggregation object */Public void next (); /*** determine whether the last position of the aggregated object has been moved * @ return true indicates that the last position of the aggregated object has been moved, * false indicates that the object has not been moved to the last position of the aggregate object */Public Boolean isdone (); /*** get the current element of the iteration * @ Return Current element of the iteration */public object currentitem ();}
4.2 two specific implementation interface classes: An array and a set

These two classes are basically the same, so it is no problem to replace them with one class.

Package demo13.iterator. example3;/*** used to implement the iterative interface for accessing arrays */public class arrayiteratorimpl implements iterator {/*** used to store the aggregated objects to be iterated */private salarymanager aggregate = NULL; /*** index used to record the current iteration position *-1 indicates that at the beginning, the iterator points to the first object of the aggregation object */private int Index =-1; public arrayiteratorimpl (salarymanager aggregate) {This. aggregate = aggregate;} public void first () {Index = 0;} public void next () {If (index <this. aggregate. size () {Index = index + 1 ;}} public Boolean isdone () {If (Index = This. aggregate. size () {return true;} return false;} public object currentitem () {return this. aggregate. get (INDEX );}} **************************************** **************************************** * ************* package demo13.iterator. example3;/*** is used to implement iterative interfaces for accessing collection sets, for unified external access */public class collectioniteratorimpl implements iterator {/*** used to store the aggregated objects to be iterated */private paymanager aggregate = NULL; /*** used to record the index at the position of the current iteration-1 indicates that at the beginning, the iterator points to the first object of the aggregation object */private int Index =-1; public collectioniteratorimpl (paymanager aggregate) {This. aggregate = aggregate;} public void first () {Index = 0;} public void next () {If (index <this. aggregate. size () {Index = index + 1 ;}} public Boolean isdone () {If (Index = This. aggregate. size () {return true;} return false;} public object currentitem () {return this. aggregate. get (INDEX );}}
4.3 define an interface for obtaining access Aggregation
Package demo13.iterator. example3;/*** interface for aggregating objects, define the interface for creating the corresponding iterator object */public abstract class aggregate {/*** factory method, create the corresponding iterator object interface * @ return interface of the corresponding iterator object */public abstract iterator createiterator ();}
4.4 modify the paymanager and salarymanager classes respectively

Added a constructor, changed the get method, and added the size method.

Package demo13.iterator. example3; import Java. util. *;/*** existing salary management object of the customer */public class paymanager extends aggregate {/*** aggregation object, here is the Java Collection object */private list = new arraylist ();/*** get the salary list * @ return salary list */public list getpaylist () {return list;}/*** calculate the salary. In fact, there should be many parameters. To demonstrate how to calculate the salary from simple */Public void calcpay, and fill in the salary information in the salary list // for testing, do some false data into the paymodel PM1 = new paymodel (); pm1.setpay (3800); pm1.setusername ("James "); paymodel PM2 = new paymodel (); pm2.setpay (5800); pm2.setusername (""); list. add (PM1); list. add (PM2);} public iterator createiterator () {return New collectioniteratorimpl (this);} public object get (INT index) {object retobj = NULL; If (index <this. list. size () {retobj = This. list. get (INDEX) ;}return retobj;} public int size () {return this. list. size ();}} **************************************** * **************************** package demo13.iterator. example3; /*** salary management class of the company acquired by the customer */public class salarymanager extends aggregate {/*** use array management */private paymodel [] PMS = NULL; /*** get the salary list ** @ return salary list */Public paymodel [] getpays () {return PMS;}/*** calculate the salary. In fact, there should be many parameters, to demonstrate how to calculate the salary from simple */Public void calcsalary () {// and fill the salary information in the salary list. // to test, do some false data into paymodel PM1 = new paymodel (); pm1.setpay (2200); pm1.setusername ("Wang Wu"); paymodel PM2 = new paymodel (); pm2.setpay (3600 ); pm2.setusername ("Zhao "); PMS = new paymodel [2]; PMS [0] = PM1; PMS [1] = PM2;} public iterator createiterator () {return New arrayiteratorimpl (this);} public object get (INT index) {object retobj = NULL; If (index <PMS. length) {retobj = PMS [Index];} return retobj;} public int size () {return this. PMS. length ;}}
4.5 The client is as follows:
Package demo13.iterator. example3; import Java. util. *; public class client {public static void main (string [] ARGs) {// access the group's salary list paymanager = new paymanager (); // obtain the paymanager after calculation. calcpay (); system. out. println ("group payroll:"); test (paymanager. createiterator (); // access the salary list of the newly acquired company salarymanager = new salarymanager (); // calculate and then obtain salarymanager. calcsalary (); system. out. println ("list of newly acquired company salaries:"); test (salary Manager. createiterator ();}/*** test the iterator that accesses the aggregate object, whether the aggregation object can be accessed normally * @ Param it the iterator of the aggregation object */Private Static void test (iterator it) {// cyclically output the value in the aggregate object // first set the iterator to the first element it. first (); While (! It. isdone () {// retrieve the current element to object OBJ = it. currentitem (); system. out. println ("the OBJ =" + OBJ); // If the iteration has not reached the end, it will be iterated down. next ();}}}
4.6 code structure

You can see the graph at a glance.
 
5. iterator mode 5.1 key points

Traverse aggregate objects in different ways
Multi-state iteration: An Iteration interface can be used to access different aggregation structures.
Key idea: separates the traversal and access of the aggregate object from the aggregate object and puts it in a separate iterator.
5.2 advantages of the iterator Mode

Better Encapsulation
Simplified aggregate Interfaces
Different traversal methods can be used to traverse an aggregation.
5.3 essence of the iterator Mode

Controls elements in an access aggregation object

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.