一个餐厅集团,有早餐、晚餐和咖啡三种餐厅类型,每种餐厅的菜单都是由MenuItem组成的,但三种餐厅实现自己的菜单时有自己的管理菜单项的方法,现在要整合三家餐厅以方便女侍者能方便地向顾客介绍各家菜单内容
public class MenuItem {
private String name;
private String description;
private boolean vegetarian;
private 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 boolean isVegetarian() {
return vegetarian;
}
public double getPrice() {
return price;
}
}
将三家菜单的共同部分抽象出一个抽象类——
public abstract class Menu implements Iterable
public class MorningMenu extends Menu{
private ArrayList menuItems;
public MorningMenu() {
menuItems=new ArrayList();
menuItems.add(new MenuItem("豆腐脑", "北方经典早餐", true, 2.0));
menuItems.add(new MenuItem("油条", "油炸面食,好吃又便宜", true, 3.2));
menuItems.add(new MenuItem("小笼包", "好吃的迷你肉包子", false, 6.3));
menuItems.add(new MenuItem("皮蛋瘦肉粥", "肉粥,南方人爱喝", false, 5.5));
}
@Override
public void addItem(MenuItem item){
menuItems.add(item);
}
@Override
public Iterator iterator() {
return menuItems.iterator();
}
}
晚餐店是用数组管理菜单项的——
public class DinnerMenu extends Menu {
private static final int MAX_NUM=64;
private int index=0;
private MenuItem[] menuItems;
public DinnerMenu() {
menuItems=new MenuItem[MAX_NUM];
addItem(new MenuItem("扬州炒饭","香肠黄瓜炒饭",false,10.0));
addItem(new MenuItem("素炒饼", "白菜和炒饼", true, 7));
addItem(new MenuItem("牛肉面", "拉面上面有一丢丢牛肉点缀", false, 12));
}
@Override
public void addItem(MenuItem item){
if(index iterator() {
return new DinnerMenuIterator();
}
private class DinnerMenuIterator implements Iterator{
private int cursor=0;
@Override
public boolean hasNext() {
return cursor
public class CafaMenu extends Menu {
private HashMap menuItems;
private int index=0;
public CafaMenu() {
menuItems=new HashMap();
addItem(new MenuItem("拿铁", "拿铁咖啡是意大利浓缩咖啡与牛奶的经典混合", true, 9.5));
addItem(new MenuItem("摩卡", "意大利浓缩咖啡、巧克力酱、鲜奶油和牛奶混合而成", true, 10));
}
@Override
public void addItem(MenuItem item) {
menuItems.put(index++, item);
}
@Override
public Iterator iterator() {
return menuItems.values().iterator();
}
}
public class Waitress {
private ArrayList
public class Client {
public static void main(String[] args) {
Waitress waitress=new Waitress();
System.out.println("全部菜单");
waitress.printMenu();
System.out.println("素食清单:");
waitress.printVegetarianMenu();
}
}