[Design pattern] iterator)

Source: Internet
Author: User

The iterator is defined as a method that provides continuous access to aggregate object elements without exposing the underlying Implementation of the object.

Provide a way to access the elements ofAggregate objectSequentially withoutexposing its underlying representation.

From the definition, we can see that iterator has three keywords: Aggregate object (aggregate object), which is defined in head first:

When we say collection we just mean a group of objects. They might be stored in very different data structures lik
E lists, arrays, HashTables, but they're still collegate. We also sometimes call these aggregate.

Simply put, a container is an aggregate object.

The second keyword is sequentially. The iterator must be able to track the elements to be accessed.

The third keyword is exposure. The iterator hides the object aggregation method. That is to say, the customers who use the iterator cannot know whether the object is aggregated in an array or a list.

The key to the iterator mode is to follow the design principle of single responsibility:

The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it intoIteratorObject. -- <Design Patterns>

Assign each responsibility to one class and only one class. --

A single responsibility allows the iterator to focus more on accessing element tasks. Therefore, it can implement various access methods without changing the client code, and provides a unified access method.

The iterator can be seen as an extension of an aggregate object.

An iterator can be viewed as an extension of the aggregate that created it.

The iterator contains too much content, which can be divided into external and internal. External requires the client to iterate, while internal only needs to call a method. The iteration process is transparent to the client.

Example

First define an iterator interface interator

public interface Iterator {    boolean hasNext();    Object next();}

Type to be iterated, menu item.

public class MenuItem {    String name;    String description;    boolean vegetarian;    double price;    public MenuItem(String name,                    String description,                    boolean vegetarian,                    double price) {        this.name = name;        this.description = description;        this.vegetarian = vegetarian;        this.price = price;    }    public String getName() {        return name;    }    public String getDescription() {        return description;    }    public double getPrice() {        return price;    }    public boolean isVegetarian() {        return vegetarian;    }}

Define a menu, which stores the menu items.

public class DinerMenu {    static final int MAX_ITEMS = 6;    int numberOfItems = 0;    MenuItem[] menuItems;    public DinerMenu() {        menuItems = new MenuItem[MAX_ITEMS];        addItem("Vegetarian BLT",            "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);        addItem("BLT",            "Bacon with lettuce & tomato on whole wheat", false, 2.99);        addItem("Soup of the day",            "Soup of the day, with a side of potato salad", false, 3.29);        addItem("Hotdog",            "A hot dog, with saurkraut, relish, onions, topped with cheese",            false, 3.05);        //a couple of other Diner Menu items added here    }    public void addItem(String name, String description,                        boolean vegetarian, double price) {        MenuItem menuItem = new MenuItem(name, description, vegetarian, price);        if (numberOfItems >= MAX_ITEMS) {            System.err.println("Sorry, menu is full! Can't add item to menu");        } else {            menuItems[numberOfItems] = menuItem;            numberOfItems = numberOfItems + 1;        }    }//      public MenuItem[] getMenuItems() {//          return menuItems;//      }    public Iterator createIterator() {        return new DinerMenuIterator(menuItems);    }    // other menu methods here}

Define another menu

import java.util.ArrayList;public class PancakeHouseMenu {    ArrayList menuItems;    public PancakeHouseMenu() {        menuItems = new ArrayList();        addItem("K&B's Pancake Breakfast",            "Pancakes with scrambled eggs, ant toast",            true,            2.99);                addItem("Regular Pancake Breakfast",            "Pancakes with fired eggs, sausage",            false,            2.99);        addItem("Blueberry Pancakes",            "Pancakes made with fresh bluebarries",            true,            3.49);        addItem("Waffles",            "Waffles, with your choice of blueberries or strawberries",            true,            3.59);    }    public void addItem(String name, String description,                        boolean vegetarian, double price) {        MenuItem menuItem = new MenuItem(name, description, vegetarian, price);        menuItems.add(menuItem);    }//    public ArrayList getMenuItems() {//        return menuItems;//    }    public Iterator createIterator() {        return new PancakeMenuIterator(menuItems);    }    // other menu methods here}

Menu iterator

import java.util.ArrayList;public class PancakeMenuIterator implements Iterator {    ArrayList items;    int position = 0;    public PancakeMenuIterator(ArrayList items) {        this.items = items;    }    public Object next() {        return items.get(position++);    }    public boolean hasNext() {        return position < items.size();    }}

public class Waitress {    PancakeHouseMenu pancakeHouseMenu;    DinerMenu dinerMenu;    public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) {        this.pancakeHouseMenu = pancakeHouseMenu;        this.dinerMenu = dinerMenu;    }    public void printMenu() {        Iterator pancakeIterator = pancakeHouseMenu.createIterator();        Iterator dinerIterator = dinerMenu.createIterator();        System.out.println("MENU\n---\nBREAKFAST");        printMenu(pancakeIterator);        System.out.println("\nLUNCH");        printMenu(dinerIterator);    }    private void printMenu(Iterator iterator) {        while (iterator.hasNext()) {            MenuItem menuItem = (MenuItem)iterator.next();            System.out.println(menuItem.getName() + ", ");            System.out.println(menuItem.getPrice() + " -- ");            System.out.println(menuItem.getDescription());        }    }    // other methods here}

Test code

public class MenuTestDrive {    public static void main(String[] args) {        PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();        DinerMenu dinerMenu = new DinerMenu();        Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);        waitress.printMenu();    }}

From the code, we can see that the client code waitress does not need to care about the aggregation of each menu object. You only need to call the corresponding traversal tool.

The next composite mode will continue to use the 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.