Headfirst java设计模式-迭代器模式

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

代码实现:
(1)先定义一个menu接口

public interface Menu {
      public Iterator createIterator();
}

(2)定义一个MenuItem类,用于存储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;
    }

    public String getName() {
        return name;
    }

    public String getDescription(){
        return description;
    }

    public double getPrice(){
        return price;
    }

    public boolean isVegetarian(){
        return vegetarian;
    }

}

(2)继承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.out.println("Sorry, menu is full! Can't add item to menu");
        } else {
            menuItems[numberOfItems] = menuItem;
            numberOfItems = numberOfItems + 1;
        }
    }

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

public class CafeMenu implements Menu{
    Hashtable menuItems = new Hashtable();

    public CafeMenu() {
        addItem("Veggie Burger and air Fries", 
                "Veggie burger on a whole wheat bun, lettuce, tomato, and fries", true, 3.99);
        addItem("Soup of the day", "A cup of soup of the day, with a side salad",
                false,3.69);
        addItem("Burrito", "A large burrito, with whole pinto beans, salsa, guacamole",
                true, 4.29);
    }

    public void addItem(String name, String description, 
                            boolean vegetarian, double price)
    {
        MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
        menuItems.put(menuItem.getName(), menuItem);
    }

    @Override
    public Iterator createIterator() {
        // TODO Auto-generated method stub
        return menuItems.values().iterator();
    }

}

public class PancakeHouseMenu implements Menu{
    ArrayList<MenuItem> menuItems;

    public PancakeHouseMenu(){
        menuItems = new ArrayList<MenuItem>();

        addItem("K&B's Pancake Brakefast",
                "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("Waffes",
                "Waffes, 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 menuItems.iterator();
    }
}

(3)由于DinerMenu采用数组存储不存在iterator,所以自己实现一个DinnerMenuIterator

import java.util.Iterator;

public class DinnerMenuIterator implements Iterator {
    MenuItem[] items;
    int position;

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

    @Override
    public boolean hasNext() {
        // TODO Auto-generated method stub
        if (position >= items.length || items[position] == null){
            return false;
        } else {
            return true;
        }
    }

    @Override
    public Object next() {
        // TODO Auto-generated method stub
        MenuItem menuItem = items[position];
        position = position + 1;
        return menuItem;
    }

    public void remove() {
        if (position < 0) {
            throw new IllegalStateException
                        ("You can't remove an item until you've done 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;
        }
    }

}

(4)创建一个watress类专门便利menu的内容

public class Waitress {
    ArrayList menus;

    public Waitress(ArrayList menus){
        this.menus = menus;
    }

    public void printMenu(){
        Iterator menuIterator = menus.iterator();
        while (menuIterator.hasNext()) {
            Menu menu = (Menu)menuIterator.next();
            printMenu(menu.createIterator());
        }
    }

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

(5)测试代码

import java.util.ArrayList;

public class MenuTestDrive {
    public static void main(String args[]) {
          PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
          DinerMenu dinerMenu = new DinerMenu();
          CafeMenu cafeMenu = new CafeMenu();
          ArrayList menus = new ArrayList();
          menus.add(pancakeHouseMenu);
          menus.add(dinerMenu);
          menus.add(cafeMenu);

          Waitress waitress = new Waitress(menus);
          waitress.printMenu();
    }
}

测试结果:
K&B’s Pancake Brakefast,
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
Waffes,
3.59 –
Waffes, with your choice of blueberries or strawberries
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
Soup of the day,
3.69 –
A cup of soup of the day, with a side salad
Burrito,
4.29 –
A large burrito, with whole pinto beans, salsa, guacamole
Veggie Burger and air Fries,
3.99 –
Veggie burger on a whole wheat bun, lettuce, tomato, and fries

猜你喜欢

转载自blog.csdn.net/MoonShinesOnMyWay/article/details/81316938