背景:
继上一集俩餐厅合并了菜单之后,现在我们有想在午餐的菜单中加一份子菜单——甜点。
设计:
- 需要树形结构可以容纳菜单、子菜单和菜单项;
- 需要确定能够在每个菜单的各个项之间游走,要像迭代器一样方便;
- 需要更加弹性的游走,如指遍历甜点或者可以遍历餐厅的整个菜单。
实现:
// 抽象类 实现菜单组件
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;
public MenuItem(String name,String description, boolean vegetarian, double price){
this.name = name;
this.description = description;
this.vegetarian = vegetarian;
this.price = price;
}
// 省略一堆get set函数
public void print() {
System.out.println("...");
}
}
// 定义组合菜单
public class Menu extends MenuComponent {
private ArrayList menuComponents = new ArrayList();
private String name;
private String description;
public Menu(String name, String description){
this.name = name;
this.description = description;
}
public void remove(MenuComponent menuComponent){
menuComponents.remove(menuComponen);
}
public MenuComponent getChild(int i){
return (MenuComponent)menuComponents.get(i);
}
public void print(){
System.out.printlin(...);
Iterator iterator = menuComponents.iterator(); // 因为他有孩子节点
while(iterator.hasNext()){
MenuComponent menuComponent = (MenuComponent)iterator.next();
menuComponent.print();
}
}
}
public class Waitress {
MenuComponent allMenus;
public Waitress(MenuComponent allMenus){
this.allMenus = allMenus;
}
public void printMenu(){ // 只需要调用顶层菜单即可。
allMenus.print();
}
}
组合模式不但要管理层次结构,还要执行菜单的操作,所以组合模式是以单一责任设计原则换取透明性。透明性是指通过让组件的接口同时包含一些管理子节点和叶子节点的操作,客户可以将组合和也节点一视同仁。
MenuComponent类同时具有两种类型的操作,因为客户有机会对一个元素做一些不恰当的操作(如试图把菜单添加到菜单项中),所以我们会失去一些安全性,这是设计上抉择。我们可以把责任区分开来放入不同的接口,这样设计安全,但是也失去了透明性,客户必须判断以处理不同类型的节点。
所以这是一个很典型的折衷案例。
我们在处理的时候,可以采用空迭代器(一直返回false)来代替返回null。
总结:
组合模式:允许你将对象组合成树形结构来表现“整体/部分”层次结构,组合能让客户一一致的方式处理个别对象以及对象组合。
组合模式让我们能用树形方式创建对象的结构,树里面包含了组合以及个别的对象。
使用组合结构,我们能把相同的操作应用到组合和个别对象上。换句话说,在大多数情况下,我们可以忽略对象组合和个别对象之间的差别。
组合模式让客户生活的更加简单,让他们不需要操心面对的是组合对象还是叶节点对象。
在实现组合模式时,有许多折衷的设计,需要平衡透明性和安全性。