Iterator mode-demo

We continue with the last example of the iterator pattern to optimize it, this time we use the iterator that comes with java

Because the collection in the PancakeHouseMenu class is ArrayList type, you can directly use the java default iterator, without writing its iterator

The collection type in DinerMenu is an array, and the java default iterator does not support the iteration of the array, you need to customize the iterator

Let's reorganize the categories

The first is the menu item class, it has no changes

package iterator.demo;
 
/**
 * 菜单项
 */
public class MenuItem
{
	private String name;              //菜单项名称
	private String description;       //描述
	private double price;             //价格
 
	public MenuItem(String name,
                    String description,
                    double price)
	{
		this.name = name;
		this.description = description;
		this.price = price;
	}
 
	public String toString()
	{
		return (name + ": "+description+", $" + price);
	}
}

 Next is the menu class

package iterator.demo;
import java.util.Iterator;
 
public interface Menu
{
     /**
      * 添加菜单项
      * @param name
      * @param description
      * @param price
      */
     void addItem(String name, String description, double price);
 
     /**
      * 获取菜单项集合
      */
     Object getMenuItems();
 
     /**
      * 获取迭代器
      * @return
      */
      Iterator<MenuItem> createIterator();
}

Then there are two restaurants, they both implement the Menu interface, the collection class used by the pancake house restaurant supports iterators, and the array used by the country restaurant does not support the iterator that comes with java.

package iterator.demo;
import java.util.ArrayList;
import java.util.Iterator;
 
/**
 * 煎饼屋餐厅
 */
public class PancakeHouseMenu implements Menu
{
	private ArrayList<MenuItem> menuItems;
 
	public PancakeHouseMenu()
	{
		menuItems = new ArrayList();
    
		addItem("薄煎饼早餐",
			"薄煎饼、鸡蛋和土司",
			2.99);
 
		addItem("蓝莓薄煎饼",
			"新鲜蓝莓和蓝莓果酱做成的薄煎饼",
			2.99);
 
		addItem("松饼",
			"松饼,可以选择蓝莓或者草莓口味",
			3.59);
	}
 
	public void addItem(String name, String description, double price)
	{
		MenuItem menuItem = new MenuItem(name, description, price);
		menuItems.add(menuItem);
	}
 
 
	public ArrayList<MenuItem> getMenuItems()
	{
		return menuItems;
	}
 
	public Iterator createIterator() {
		return  menuItems.iterator();
	}
}
package iterator.demo;


import java.util.Iterator;

/**
 * 对象村餐厅
 */
public class DinerMenu implements Menu
{
    private static final int MAX_ITEMS = 4;
    private int numberOfItems = 0;
    private MenuItem[] menuItems;
  
	public DinerMenu() {
		menuItems = new MenuItem[MAX_ITEMS];
 
		addItem("素食 BLT", "(煎)培根, 生菜和西红柿",  2.99);
		addItem("清汤", "一碗清汤, 配土豆沙拉", 3.29);
		addItem("热狗", "一个热狗, 酸菜, 芝士, 洋葱",  3.05);
		addItem("清蒸时蔬加糙米", "清蒸的蔬菜配糙米", 3.99);
	}
  
	public void addItem(String name, String description, double price)
	{
		MenuItem menuItem = new MenuItem(name, description,  price);
		if (numberOfItems >= MAX_ITEMS)
		{
			System.err.println("抱歉, 菜单已满! 不能添加菜单项");
		}
		else
		{
			menuItems[numberOfItems] = menuItem;
			numberOfItems = numberOfItems + 1;
		}
	}
 
	public MenuItem[] getMenuItems()
	{
		return menuItems;
	}

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

 Since the village restaurant DinerMenu is an array type collection, you need to customize an iterator and implement the Iterator interface

package iterator;

import item.MenuItem;

import java.util.Iterator;

public class DinerMenuIterator implements Iterator
{
    private MenuItem[] menuItems;
    private int position = 0;

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

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

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

Let's take a look at the waitress. We changed the specific type to the interface type, so that "by programming for the interface, not for the realization of programming", we can reduce the dependence between the female receptionist and the specific class

package iterator.demo;

import java.util.Iterator;

public class Waitress
{
	private Menu pancakeHouseMenu;
	private 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();
		printMenu(pancakeIterator);
		printMenu(dinerIterator);

	}

	private void printMenu(Iterator<MenuItem> iterator) {
		while (iterator.hasNext()) {
			MenuItem menuItem = iterator.next();
			System.out.println(menuItem);
		}
	}

}

The final test class, the waitress can also complete the previous function according to the incoming restaurant newspaper menu

package iterator.demo;


public class Client
{
    public static void main(String[] args)
    {
        PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
        DinerMenu dinerMenu = new DinerMenu();

        Waitress waitress=new Waitress(pancakeHouseMenu,dinerMenu);
        waitress.printMenu();
    }
}

In fact, there is still room for improvement in the waitress. Every time you add a new restaurant, you have to modify the contents of the waitress, which does not meet the opening and closing principles

 

Re-optimize and turn multiple restaurants into a restaurant collection, so that each time you add a restaurant category, you do n’t need to modify the waitress.

package iterator.demo;


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

/**
 * 服务员类,根据餐厅打印菜单
 */
public class Waitress
{
	ArrayList<Menu> menus;

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


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

	}

	private void printMenu(Iterator<MenuItem> iterator) {
		while (iterator.hasNext()) {
			MenuItem menuItem = iterator.next();
			System.out.println(menuItem);
		}
	}
}

 The test class is a little more troublesome, but there is no need to modify the waitress, and the principle of opening and closing is realized

package iterator.demo;

import java.util.ArrayList;

public class Client
{
    public static void main(String[] args)
    {

        PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
        DinerMenu dinerMenu = new DinerMenu();
        ArrayList list = new ArrayList();
        list.add(pancakeHouseMenu);
        list.add(dinerMenu);

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

 

Published 138 original articles · praised 34 · 150,000 views

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105162657