迭代器模式

迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露其内部的表示。

示例—合并两种菜单

有两种餐厅菜单,分别用数组和ArrayList实现。现在需要合并两种菜单,且合并后可以让一个女招待的类去访问,不需要重复代码就可以同时访问两种菜单。

UML图表示

迭代器模式_第1张图片
迭代器模式-合并菜单

代码演示

菜单项类

package Menu;

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;
    }

    @Override
    public String toString() {
        return name + ", " + price + " -- " + description;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public boolean isVegetarian() {
        return vegetarian;
    }

    public double getPrice() {
        return price;
    }
}

菜单接口

package Menu;

import java.util.Iterator;

public interface Menu {
    Iterator createIterator();
}

午餐厅菜单

package Menu;

import java.util.Iterator;

public class DinerMenu implements Menu {
    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);
    }

    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++;
        }
    }

    public Iterator createIterator(){
        return new DinerMenuIterator(menuItems);
    }

}

午餐厅迭代器

package Menu;

import java.util.Iterator;
import java.util.List;

public class DinerMenuIterator implements Iterator {

    MenuItem[] items;
    int position = 0;

    public DinerMenuIterator(MenuItem[] items) {
        this.items = items;
    }

    @Override
    public boolean hasNext() {
        if (position >= items.length || items[position] == null)
            return false;
        else
            return true;
    }

    @Override
    public Object next() {
        MenuItem menuItem = items[position];
        position = position + 1;
        return menuItem;
    }

    @Override
    public void remove() {
        if (position <= 0){
            throw  new IllegalStateException("You can't remove an item until you've at least one next()");
        }
        if (items[position - 1] != null){
            for (int i = position - 1; i < (items.length - 1); i++){
                items[i] = items[i + 1];
            }

            items[items.length - 1] = null;
        }
    }
}

煎饼屋菜单类

package Menu;

import java.util.ArrayList;
import java.util.Iterator;

public class PancakeHouseMenu implements Menu {
    ArrayList menuItems;

    public PancakeHouseMenu(){
        menuItems = new ArrayList();

        addItem("K&B's Pancake Breakfast",
                "Pancakes with scrambled eggs, and toast",
                true,2.99);
        addItem("Regular Pancake Breakfast",
                "Pancakes with fired eggs, sausage",
                false,2.99);
        addItem("Blueberry Pancakes",
                "Pancakes made with fresh blueberries",
                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 PancakeHouseMenuIterator createIterator() {
//        return new PancakeHouseMenuIterator(menuItems);
//    }

    public Iterator createIterator() {
        return menuItems.iterator();
    }
}

煎饼屋迭代器(可用系统迭代器代替)

package Menu;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class PancakeHouseMenuIterator implements Iterator {

    private ArrayList menuItems;
    private int position = 0;

    public PancakeHouseMenuIterator(ArrayList menuItems){
        this.menuItems = menuItems;
    }

    @Override
    public boolean hasNext() {
        if (position >= menuItems.size() || menuItems.get(position) == null)
            return false;
        else
            return true;
    }

    @Override
    public Object next() {
        MenuItem item = menuItems.get(position);
        position++;
        return item;
    }

    @Override
    public void remove() {

    }
}

服务生类

package Menu;

import java.util.Iterator;

public class Waitress {

    Menu pancakeHouseMenu;
    Menu dinerMenu;

    public Waitress(Menu pancakeHouseMenu, Menu 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);
    }

    public void printMenu(Iterator iterator) {
        while (iterator.hasNext()) {
            MenuItem menuItem = (MenuItem) iterator.next();
            System.out.print(menuItem.getName() + ", ");
            System.out.print(menuItem.getPrice() + " -- ");
            System.out.println(menuItem.getDescription());
        }
    }

}

测试代码

package Menu;

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

测试结果

MENU
----
BREAKFAST
K&B's Pancake Breakfast, 2.99 -- Pancakes with scrambled eggs, and toast
Regular Pancake Breakfast, 2.99 -- Pancakes with fired eggs, sausage
Blueberry Pancakes, 3.49 -- Pancakes made with fresh blueberries
Waffles, 3.59 -- Waffles, with your choice of blueberries or strawberries

LUNCH
Vegetarian BLT, 2.99 -- (Fakin')Bacon with lettuce & tomato on whole wheat
BLT, 2.99 -- Bacon with lettuce & tomato on whole wheat
Soup of the day, 3.29 -- Soup of the day, with a side of potato salad
Hotdog, 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese

你可能感兴趣的:(迭代器模式)