今天在看head first设计模式,发现在组合模式中,有段代码有问题,是在书的第369页,我利用书中的CompositeIterator来遍历MenuComponent时候,apple pie会打印两次,个人认为是在hasNext()实现的时候,漏pop了一个迭代器。我不知道是哪里错了,为何在有嵌套的对象中,嵌套对像会被打印两次呢?
@
Override public boolean hasNext() {
// TODO Auto-generated method stub
if (stack.empty()) {
return false;
} else {
Iterator<MenuComponent> iter = stack.peek();
if (!iter.hasNext()) {
this.stack.pop();
return hasNext();
} else {
return true;
}
}
}
@
Override public MenuComponent next() {
// TODO Auto-generated method stub
if (hasNext()) {
Iterator<MenuComponent> iter = stack.peek();
MenuComponent component = iter.next();
if(component instanceof MenuItem&&component.getName().equals("Apple pie")){
System.out.println("hello");
}
if (component instanceof Menu) {
stack.push(component.createIterator());
}
return component;
} else {
return null;
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Menu menu1=new Menu("Pancake house menu", "Breakfase");
Menu menu2=new Menu("Diner menu","Lunch");
Menu menu3=new Menu("Cafe menu", "Dinner");
Menu menu4=new Menu("Dessert menu", "dessert of course");
Menu allMenus=new Menu("All menus", "All menu combined");
allMenus.add(menu1);
allMenus.add(menu2);
allMenus.add(menu3);
menu2.add(new MenuItem("Pasta", "blarblarblarblar", true, 3.89));
menu2.add(menu4);
menu4.add(new MenuItem("Apple pie", "blarblarblarblar", true, 1.59));
Waitress w=new Waitress(allMenus);
w.printVegetarianMenu();
}
public class Waitress {
MenuComponent allMenus;
public Waitress(MenuComponent mc){
this.allMenus=mc;
}
public void printMenu(){
allMenus.print();
}
public void printVegetarianMenu() throws Exception{
Iterator<MenuComponent> iter=allMenus.createIterator();
int i=0;
while(iter.hasNext()){
if(i==2){
i++;
}
MenuComponent mc=iter.next();
try{
if(mc.isVegetarian()){
i++;
mc.print();
}
}catch(UnsupportedOperationException ex){}
}
}
}
menu 4里面的apple pie会被打印两次,这是为什么呢?