迭代器模式:
让用户通过特定的接口访问容器的数据,不需要了解容器内部的数据结构。
比如menu里有早餐的Array和完成的ArrayList,遍历时需要用分别用遍历数组和ArrayList(遍历两次),且如果增加甜品的HashMap时需要修改menu的代码。
可以让数组,ArrayList和HashMap等实现迭代器接口,在menu里设置迭代器的数组或list,通过迭代器遍历一次即可(可简写成for in遍历)。
组合模式:
DrinkComponent 里默认的方法实现时直接报错,因为DrinkMenu需要实现addChild(需要重写),而DrinkItem不应该有这个方法。所以让DrinkItem调用addChild时报错是很好的解决方案。
public abstract class DrinkComponent {
public void getNames(String prefix) {
throw new UnsupportedOperationException();
}
public void addChild(DrinkComponent d){
throw new UnsupportedOperationException();
}
}
public class DrinkMenu extends DrinkComponent{
private String name;
private List<DrinkComponent> drinkComponents=new ArrayList<>();
public DrinkMenu(String name) {
this.name = name;
}
@Override
public void getNames(String prefix) {
System.out.println(prefix+">"+name);
for(DrinkComponent dc:drinkComponents){
dc.getNames("--"+prefix);
}
}
@Override
public void addChild(DrinkComponent d) {
drinkComponents.add(d);
}
}
public class DrinkItem extends DrinkComponent{
private String name;
public DrinkItem(String name) {
this.name = name;
}
@Override
public void getNames(String prefix) {
System.out.println(prefix+">"+name);
}
}
public class Testt {
@Test
public void oo(){
DrinkComponent coffeeMenu=new DrinkMenu("coffeeMenu");
DrinkComponent cocoa=new DrinkMenu("cocoa");
DrinkComponent hotCocoa=new DrinkItem("hotCocoa");
DrinkComponent hotoCocoa=new DrinkItem("hotoCocoa");
DrinkComponent chino=new DrinkMenu("chino");
cocoa.addChild(hotCocoa);
cocoa.addChild(hotoCocoa);
coffeeMenu.addChild(cocoa);
coffeeMenu.addChild(chino);
DrinkComponent teaMenu=new DrinkMenu("teaMenu");
DrinkComponent menu=new DrinkMenu("menu");
menu.addChild(coffeeMenu);
menu.addChild(teaMenu);
menu.getNames("");
/*
>menu
-->coffeeMenu
---->cocoa
------>hotCocoa
------>hotoCocoa
---->chino
-->teaMenu*/
}
}