Java design pattern-iterator pattern Parsing

Source: Internet
Author: User

Java design pattern-iterator pattern Parsing
Overview

Most people on the Internet say that when the iteration mode is used, an object that can be traversed is always used as an example. This is feasible, and it is also the basic prototype of the iteration mode. When I see the iteration mode in Head Frist design mode, I feel that if I can explain it from another perspective, it may better reflect the power of the iteration mode.

This iteration mode described in this article is more likeAdapter-iterator Mode. Hope you will benefit ~

Description

Most articles about the iterator mode on the Internet are based on a List or other iteratable objects. In this case, there is a problem because they are all iteratable objects. During the iteration process, we cannot find out what problems the iterator mode can solve for us. The following example shows the power of the iterator mode.

1. instance background

There are two restaurants A and B. Restaurant A is A breakfast restaurant, while restaurant B is A lunch restaurant.

Now the big Boss of the two restaurants decided to merge them. In restaurant A, the logical implementation of menus is based on ArrayList, while that of restaurant B is based on arrays. If you modify the menu implementation of any restaurant, unnecessary modifications may be triggered, and such modifications may lead to unnecessary bugs, therefore, neither A nor B is willing to modify the original menu implementation.

Now, we need to easily traverse menus without changing the menu implementation of the two restaurants.

-- From Head Frist Design Pattern

2. Train of Thought Analysis

What's the problem? ArrayList and array are both objects that can be traversed cyclically. Can we traverse these two arrays in sequence?

It is undeniable that this is the simplest implementation logic and is easy to understand. But is this really good? What if there are 100 restaurants? We hope that the menu can be traversed more conveniently and elegantly. We hope that in later projects, code maintenance will be higher, rather than being "rotten.

We think that if our ArrayList and array can have a public interface, then we can use this public interface to iterate, so that the code reusability is not higher? But how to find such an interface? When I learned about the class and interface in objective Java, the Book of God, I learned that in our program, combination is better than inheritance. Therefore, we can combine ArrayList and array into different menus. In this way, the menu traversal is the traversal of ArrayList or array.

Because ArrayList itself contains an iterator, we do not need to create an iterator for ArrayList. There is no such iteration logic in the array, so we need to create an iterator for the array.

 

3. Class Diagram

Based on the above analysis, we can draw the following class diagram:

Figure-1 iterator pattern class diagram

4. Logical implementation (1) Write Public Interfaces

The Menu interface is left at the first position in the class diagram. The purpose of adding this interface is to improve code reusability. This is done at (4 ).Iteration Logic. The public interface code is as follows:

 

public interface Menu {    public Iterator createIterator();}

 

(2) create an iterator

In the above class diagram, we can find the BreakfastMenu and LunchMenu menus, both of which implement the Menu interface. However, because they contain different container objects (BreakfastMenu contains ArrayList and LunchMenu contains arrays), they are different when creating the iterator.

Let's take a look at the logic code of BreakfastMenu to create an iterator, as shown below:

 

@Override    public Iterator createIterator() {        return menuItems.iterator();    }
Because ArrayList itself contains the implementation of the iterator, The iterator of ArrayList can be directly returned here. The array does not have the implementation Part Of The iterator, so it is different from the above creation method, as shown below:

 

 

@Override    public Iterator createIterator() {        return new LunchIterator(menuItems);    }

 

(3) custom iterator

Because arrays do not have iteration functions, we need to expand them. However, if you want to "iterate" an array, its fundamental implementation still depends on the loop traversal of the array. Because only this method can be used to extract elements from arrays in sequence. There are two core methods in the iterator: hasNext () and next (). Therefore, we use these two methods to achieve array iteration in disguise. The Code is as follows:

 

public class LunchIterator implements Iterator {    private MenuItem[] menuItems = null;    private int position = 0;        public LunchIterator(MenuItem[] _menuItems) {        this.menuItems = _menuItems;    }        @Override    public boolean hasNext() {        if (menuItems == null) {            return false;        }                return position < menuItems.length;    }    @Override    public MenuItem next() {        MenuItem menuItem = menuItems[position];        position++;        return menuItem;    }}
Here is an extra defined variable position, which is used for element indexing. We need to use this variable to extract elements and complete the discriminant iteration.

 

(4) iteration Logic

The iteration logic mentioned here is the implementation logic of the client outside the iterator. Assume that we have a waitress who can print out the menus required by the customer without worrying about how the menus are implemented.

 

Public class Waitress {private IteratorIterator = null; private Menu menu = null; public Waitress (Menu _ menu) {this. menu = _ menu;} public void printMenu () {System. out. println ("\ n menu:"); iterator = menu. createIterator (); do {System. out. println (iterator. next ();} while (iterator. hasNext ());}}

 

Ref

Head Frist design patterns 23 Java Design Patterns

 

Download Github source code

Https://github.com/William-Hai/DesignPattern-Iterator

 

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.