背景:
继上一集俩餐厅合并了菜单之后,现在我们有想在午餐的菜单中加一份子菜单——甜点。
设计:
- 需要树形结构可以容纳菜单、子菜单和菜单项;
- 需要确定能够在每个菜单的各个项之间游走,要像迭代器一样方便;
- 需要更加弹性的游走,如指遍历甜点或者可以遍历餐厅的整个菜单。
实现:
// 抽象类 实现菜单组件
public abstract class MenuComponent {
public void add(MenuComponent menuComponent){
throw new UnsupportedOperationException();
}
public void remove(MenuComponent menuComponent){
throw new UnsupportedOperationException();
}
// 同理其它方法,getChild(int i) getName() getDescription() getPrice() isVegetarian() print()
// 这样写是因为有的方法只对菜单项有意义,而有的只对菜单有意义,不支持的操作默认实现异常即可。
}
// 实现菜单项
public class MenuItem extends MenuComponent {
private String name;
private String description;
private boolean vegetarian;
private double price;
publ