Java design pattern-iterator mode

Source: Internet
Author: User

Overview

Most people on the web say that iterative patterns are always described as an example of a certain kind of object that can be traversed. This is possible, and this is the basic prototype of the iterative pattern. When I see the iterative pattern in Head frist design mode, it may be more likely to reflect the power of the iterative pattern if it can be illustrated from another angle.

The iterative pattern described in this article is more like an adapter-iterator pattern . I hope it's good for you ~


Copyright Notice

Copyright belongs to the author.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Coding-naga
Published: March 4, 2016
Links: http://blog.csdn.net/lemon_tree12138/article/details/50799562
Source: CSDN
More information: Classification >> Design Patterns


Mode Description

Most of the online articles on iterator patterns are based on a list or other iterative object. There is a problem because it is an iterative object, and in the iterative process we have no insight into what the iterator pattern can do to solve the problem for us. Here is an example of the power of the iterator pattern that may be illustrated by this example.

1. Instance Background

There are two restaurants A and B, restaurant A is a breakfast restaurant, and Restaurant B is a lunch-restaurant shop.

Now the big boss of two restaurants has decided to merge two restaurants. In restaurant A, the logical implementation of the menu is based on ArrayList, while the menu logic implementation of restaurant B is array-based. If you modify the menu implementation of any restaurant, you may have some unnecessary modifications, and this modification may lead to unnecessary bugs, so neither a nor B is willing to modify the original implementation of the menu.

The need now is to easily traverse the menu without changing the implementation of the menu in two restaurants.

--from "Head Frist design Mode"

2. Analysis of Ideas

What's so hard about this? ArrayList and arrays are iterated objects, can we iterate through the two arrays in turn?

Admittedly, this is the simplest form of implementation logic and understandable. But is this really a good way? What if there are 100 restaurants now? What we want is a more convenient and elegant way to traverse the menu, and we hope that in later projects, the code will be more maintainable, rather than always "rotten".

We think that if our ArrayList and arrays can have a common interface, then we can iterate through this common interface, so the reusability of the code is not higher? However, how to find such an interface? In learning "effective Java" This book of "Class and Interface" a single, it is understood in our program, the compound is better than inheritance. So, here we can combine ArrayList and arrays into different menus, so that the traversal of the menu is the traversal of the ArrayList or the array.

Because the ArrayList itself contains iterators, we don't need to create iterators for ArrayList here. There is no such iterative logic in the array, so we are going to create an extra iterator for the arrays.


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) public interface writing

The first position in the class diagram is left with the menu interface, and the purpose of adding this interface is to improve the reusability of the code. This is reflected in the iteration logic of Point (4). The common interface code is as follows:

Public interface Menu {public    iterator<menuitem> createiterator ();}

(2) Creation of iterators

In the class diagram above we can find the Breakfastmenu and lunchmenu two menu classes, which are implemented with the menu interface. However, because they contain different container objects (Breakfastmenu contains arraylist,lunchmenu containing arrays), they are different when creating iterators.

Let's take a look at the logic code for Breakfastmenu to create an iterator, as follows:

@Override public    iterator<menuitem> createiterator () {        return menuitems.iterator ();    }
Because the ArrayList itself contains the implementation of the iterator, it is possible to return the ArrayList iterator directly. The array does not have an implementation part of the iterator, so it will be different from how it was created, as follows:

@Override public    iterator<menuitem> createiterator () {        return new lunchiterator (MenuItems);    }

(3) Custom iterators

Since the array itself does not have an iterative function, we need to extend it. However, if you want an "iterative" array, the underlying implementation is dependent on the loop traversal of the array. Because the array has only one way to extract the elements sequentially. There are two core methods in an iterator: Hasnext () and Next (). Therefore, we use these two methods in disguise to realize the iteration of the array. The code is as follows:

public class Lunchiterator implements iterator<menuitem> {    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 additional defined variable, position, which is used to index the elements, and we need to extract the elements through this variable, and the discriminant iteration is complete.

(4) Iterative logic

The iterative logic mentioned here is the implementation logic for the client outside of the iterator. Assuming we have a waitress, she can print out the menu that the client needs without worrying about how the menu is implemented.

public class Waitress {    private iterator<menuitem> Iterator = 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 Mode"
    • "23 Java Design Patterns"


GitHub Source Download

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

Java design pattern-iterator mode

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.