Design mode (14) Iterator mode iterator (object behavior type)

Source: Internet
Author: User

Design mode (14) Iterator mode iterator (object behavior type) 1. Overview

Object-oriented programming in a class encapsulates the application logic. Class is an instantiated object, each individual object has a specific identity and state. A separate object is a useful way to organize your code, but you typically work with a set of objects or collections.

The collection is not necessarily uniform. The Window object in the graphical user interface framework can collect any number of control objects-Menu, Slider, and Button. Also, a collection can be implemented in several ways: a PHP number is a collection, but it is also a hash table, a list of links, a stack, and a queue.

Example 1: Channel traversal for TV remote control

2. Questions

How do I manipulate any collection of objects? Like a list or a collection (set), how do we provide a way for others to access its elements without exposing its internal structure?

3. Solution

Iterator mode: Use the iterator pattern to provide uniform access to the aggregated object, which provides an external iterator to access and traverse the aggregated object without exposing the object's internal structure. Also called cursor mode.
You may not be aware of this, but you are using the iterator pattern every day.
As in PHP development, it lurks in the PHP array type and various array manipulation functions. (In fact, you will have to use these arrays to manipulate the collection of objects by giving you a combination of some intrinsic classes of arrays and a bunch of mutable functions that work with these intrinsic classes.) This is an iterative iteration of the local array in PHP:

[PHP]View Plain Copy print?
    1. $test = Array (' One ', ' one ', ' one ', ' three ');
    2. $output = ";   Reset ($test);
    3. do {
    4. $output. = Current ($test);
    5. } while (Next ($test));
    6. echo $output; //produces ' Onetwothree '

The reset () function moves the iteration back to the beginning of the array, current () returns the value of the existing element, and next () advances to the next element in the array and returns the new value of the present (). When you go beyond the last element of the array, next () returns false. Using these iterative methods, the internal implementation of the PHP array is irrelevant to you.

Iterators combine encapsulation and polymorphism in object-oriented programming principles. With iterators, you can manipulate objects in a collection without having to know specifically how the collection is exposed or what the collection contains (the kind of objects). Iterators provide a uniform interface for different fixed iteration implementations, and it completely contains details about how to manipulate specific collections, including which items (filters) are displayed and their display order (sort).

4. Applicability

The iterator pattern can be used to:

• 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 (that is, support for polymorphic iterations)

5. Structure

As you can see, the iterator pattern adds an iterator role between the customer and the container. With the addition of the iterator role, it is possible to avoid exposing the details inside the container, and also make the design symbol "single responsibility Principle".

Note that in the iterator pattern, the specific iterator role and the specific container role are coupled--the traversal algorithm is closely related to the internal details of the container. In order to get the client program out of the dilemma of coupling with the specific iterator role, to avoid the change of the specific iterator role to the client program, the iterator pattern abstracts the specific iterator role, making the client program more general and reusable. This is called a polymorphic iteration .

6. Composition of the pattern

Abstract iterator (Iterator): An iterator that defines an interface for accessing and traversing elements.
Specific iterator (Concreteiterator): The concrete iterator implements the iterator iterator interface. Tracks the current position on the aggregation pass-through duration.
Abstract aggregation Class (Aggregate): An aggregation defines an interface that creates an appropriate iterator object.
Specific aggregation Class (Concreteaggregate): The body aggregation implements an interface that creates an appropriate iterator that returns an appropriate instance of Concreteiterator.

7. Effects

• The role of the iterator pattern:1) It supports traversing an aggregate object in different ways: complex aggregations can be traversed in many ways. The iterator pattern 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 yourself to support the new traversal.
2) Iterators simplify the aggregation of interfaces with an iterator traversal interface, and the aggregation itself no longer requires a similar traversal interface. This simplifies the interface of the aggregation.
3) on the same aggregation there can be multiple traversal of each iterator to maintain its own traversal state. So you can do multiple traversal at the same time. 4) 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". the drawback of the iterator pattern is that because the iterator pattern separates the responsibilities of storing data and traversing data, adding new aggregate 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.

8. Implement

We directly implement the iterator of SPL:

[PHP]View Plain Copy print?
  1. <?php
  2. /**
  3. * Specific iterator (Concreteiterator): The specific iterator implements the iterator iterator interface. Tracks the current position on the aggregation pass-through duration.
  4. */
  5. Class Concreteiterator implements Iterator {
  6. protected $_key;
  7. protected $_collection;
  8. Public function __construct ($collection) {
  9. $this->_collection = $collection;
  10. $this->_key = 0;
  11. }
  12. public function Rewind () {
  13. $this->_key = 0;
  14. }
  15. public function valid () {
  16. return isset ($this->_collection[$this->_key]);
  17. }
  18. Public Function key () {
  19. return $this->_key;
  20. }
  21. Public function current () {
  22. return $this->_collection[$this->_key];
  23. }
  24. Public function next () {
  25. return + +$this->_key;
  26. }
  27. }
  28. /**
  29. * Specific aggregation classes (concreteaggregate):
  30. */
  31. Class Concreteaggregate implements iteratoraggregate{
  32. protected $_arr;
  33. Public function __construct ($array) {
  34. $this->_arr = $array;
  35. }
  36. Public function Getiterator () {
  37. return new Concreteiterator ($this->_arr);
  38. }
  39. }
  40. $_collectionay = Array (1,2,3,3,4);
  41. $it = new Concreteiterator ($_collectionay);
  42. foreach ($it as $key = =$value) {
  43. echo $key.': '. $value.  ' <br/> ';
  44. }


9. With other related modes

Composite: iterators are often applied to recursive structures such as composites.
Factory method: A polymorphic iterator relies on Factory method to instantiate an appropriate iterator subclass.
Memento: Often used in conjunction with the iterator pattern. Iterators can use a memento to capture the state of an iteration. The iterator stores the memento inside it.

10. Summary and Analysis

1) aggregation is a data structure that manages and organizes data objects. 2) The aggregation object mainly has two responsibilities: one is to store internal data, and the other is to traverse internal data. 3) storing data is the most basic responsibility of aggregating objects. 4) 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".

Design mode (14) Iterator mode iterator (object behavior type)

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.