Design Pattern (14) Iterator pattern Iterator (object behavior pattern)

Source: Internet
Author: User

1. Overview

Class. Class is an instantiated object. Each individual object has a specific identity and status. A separate object is a useful way to organize code, but you usually process a group of objects or collections.

The set is not necessarily uniform. Window objects in the graphic user interface framework can collect any number of control objects-menu, Slider, And button. In addition, collections can be implemented in multiple ways: PhP numbers are a set, but they are also a hash list, a link list, a stack, and a queue.

Example 1: Channel traversal of the TV remote control

2. Problem

How to manipulate any object set?

For example, a list or set, how can we provide a way for others to access its elements without exposing its internal structure?

3. Solution

Iterator mode: The iterator mode is used to provide unified access to aggregate objects. That is, an external iterator is provided to access and traverse aggregate objects, the internal structure of the object does not need to be exposed. It is also called the cursor mode.
You may not be aware of this, but you are using the iterator mode every day.
For example, in PHP development, it is hidden in PHP array types and various array operation functions. (In fact, it gives you a combination of arrays of inherent classes and a group of variable functions that work with these inherent classes, and you will have to use these arrays to process object sets. This is a local array iteration in PHP:

$test  =  array(‘one’,  ‘two’,  ‘three’);$output  =  ‘’; reset($test); do  {$output  .=  current($test);}  while  (next($test));echo  $output;  //  produces  ‘onetwothree’

The reset () function re-converts the iteration to the beginning of the array; current () returns the value of the current element; next () then advances to the next element in the array and returns the new current () value. When you exceed the last element of the array, next () returns false. Using these iteration methods, the internal implementation of the PHP array is irrelevant to you.

The iterator combines encapsulation and polymorphism object-oriented programming principles. With the iterator, you can operate on objects in the set without having to know how the set appears or what the set contains (the object type ). The iterator provides a unified interface for different fixed iterations. It fully contains detailed information about how to manipulate a specific set, including the items (filtering) displayed and their display Order (sorting ).

4. Applicability

The iterator mode can be used:

• Access the content of an aggregate object without exposing its internal representation.
• Multiple traversal methods need to be provided for aggregate objects.
• Provides a unified interface for Traversing different aggregation structures (that is, supporting multi-state iteration)

5. Structure

The structure shows that the iterator mode includes the iterator role between the customer and the container. The addition of the iterator role can avoid the exposure of internal details of the container, and also make the design symbol "single responsibility principle ".

Note: In the iterator mode, the specific iterator role is coupled with the specific container role-the traversal algorithm is closely related to the internal details of the container. In order to remove the customer program from the dilemma of coupling with the specific iterator role, and to avoid modifications to the customer program due to the replacement of the specific iterator role, the iterator mode abstracts the specific iterator role, making the customer program more general and reusable. This is calledPolymorphism Iteration.

6. Composition of the Mode

Abstract iterator ):
The iterator defines interfaces for accessing and traversing elements.
Concreteiterator: a specific iterator implements the iterator interface. Tracks the current position of the aggregated time.
Abstract Aggregate class: Aggregate defines the interface for creating the corresponding iterator object.
ConcreteAggregate: implements the interface for creating the corresponding iterator for body aggregation. This operation returns an appropriate instance of ConcreteIterator.

7. Effect

• The role of the iterator mode:

1) it supports traversing an aggregate object in different ways: complex aggregation can be traversed in multiple ways. The iterator mode makes it easy to change the traversal algorithm: You only need an instance of a different iterator to replace the original Instance. You can also define the subclass of the iterator to support new traversal.
2) The iterator simplifies the aggregation interface. With the iterator's traversal interface, the aggregation itself no longer needs similar traversal interfaces. This 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. 4) In the iterator mode, it is convenient to add new aggregate classes and iterator classes. You do not need to modify the original code to meet the requirements of the "Open and Close principle.

Disadvantages of the iterator ModeBecause the iterator mode separates the responsibilities of storing and traversing data, a new aggregation class needs to be added to the new iterator class, and the number of classes increases in pairs, this increases the complexity of the system to a certain extent.

8. Implementation

We directly implement the spl iterator:

<? PHP/*** concreteiterator: a specific iterator implements the iterator interface. Tracks the current position of the aggregated time. */Class concreteiterator implements iterator {protected $ _ key; protected $ _ collection; public function _ construct ($ collection) {$ this-> _ collection = $ collection; $ this-> _ key = 0;} public function rewind () {$ this-> _ key = 0;} public function valid () {return isset ($ this-> _ Collection [$ this-> _ key]);} public function key () {return $ this-> _ key ;} public Function current () {return $ this-> _ Collection [$ this-> _ key];} public function next () {return ++ $ this-> _ key ;}/ *** specific aggregate class (concreteaggregate): */class concreteaggregate implements iteratoraggregate {protected $ _ arr; public Function _ construct ($ array) {$ this-> _ arr = $ array;} public function getiterator () {return New concreteiterator ($ this-> _ ARR) ;}}$ _ collectionay = array (1, 2, 3, 3, 4); $ it = new concreteiterator ($ _ collectionay ); foreach ($ it as $ key => $ value) {echo $ key. ':'. $ value. '<br/> ';}

9. Other related models

Composite: iterators are often applied to recursive structures such as composite.
Factory method: the multi-state iterator uses the factory method to sample the appropriate iterator subclass.
Memento: often used together with the iterator mode. The iterator can use a memento to capture the status of an iteration. The iterator stores memento internally.

10. Summary and Analysis

1) aggregation is a data structure for managing and organizing data objects. 2) Aggregation objects have two main responsibilities: one is to store internal data, and the other is to traverse internal data.
3) data storage is the most basic responsibility of aggregation objects. 4) extract the data behavior in the traversal aggregate object, encapsulate it into an iterator, and use a dedicated iterator to traverse the internal data of the aggregation object, this is the essence of the iterator mode. The iterator mode is the perfect embodiment of the "single responsibility principle.

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.