还记得我们上一章讲了迭代器模式吗。今天我们说的模式会和迭代器模式一起运用。
我们上一章说的例子是餐厅和煎饼屋合并了,如果同时咖啡厅也合并了过来,餐厅的下面又多出了一个甜品菜单,那么问题就复杂了。
我们要从新设计一下改怎么解决这个问题了
我也就不卖关子了,这个时候,一个新的模式就发挥除了他的作用---------------组合模式
组合模式:允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方法处理个别对象以及对象的组合。
使用组合模式结构,我们能把相同的操作应用在组合和个别对象上。换句话说,在大多数情况下,我们可以忽略对象组合和个别对象的差别。
让我们看看利用组合设计菜单:
接下来让我们来实现菜单组件吧。
MenuComponent类:
public abstract class MenuComponent { //这个类对每个方法提供默认的实现
public void add(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public void remove(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public MenuComponent getChild(int i) {
throw new UnsupportedOperationException();
}
public String getName() {
throw new UnsupportedOperationException();
}
public String getDescription() {
throw new UnsupportedOperationException();
}
public double getPrice() {
throw new UnsupportedOperationException();
}
public boolean isVegetarian() {
throw new UnsupportedOperationException();
}
public void print() {
throw new UnsupportedOperationException();
}
}
实现菜单类:
MenuItem类:
public class MenuItem extends MenuComponent{
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 boolean isVegetarian() {
return vegetarian;
}
public double getPrice() {
return price;
}
public void print() {
System.out.println(" " + getName());
if (isVegetarian()) {
System.out.println("(V)");
}
System.out.println(", " + getPrice());
System.out.println(" --" + getDescription());
}
}
实现组合菜单
Menu类:
public class Menu extends MenuComponent {
ArrayList menuComponents = new ArrayList();
String name;
String description;
public Menu(String name, String description) {
this.name = name;
this.description = description;
}
public void add(MenuComponent menuComponent) {
menuComponent.add(menuComponent);
}
public void remove(MenuComponent menuComponent) {
menuComponent.remove(menuComponent);
}
public MenuComponent getChild(int i) {
return (MenuComponent)menuComponents.get(i);
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void print() {
System.out.println("\n" + getName());
System.out.println(", " + getDescription());
System.out.println("-------------------");
}
}
我们就大致介绍了一下组合模式,其他还有一些类这里就不一一列举了,接下来我们来看看组合模式有什么要点吧。
总结:
1:组合模式提供一个结构,可同时包容个别对象和组合对象。
2:组合模式允许客户对个别对象以及组合对象一视同仁。
3:组合结构内的任意对象称为组件,组件可以是组合,也可以是叶节点。
4:在实现组合模式时,有许多设计上的折衷。你要根据需要平衡透明性和安全性。