迭代器模式

2021-07-15 21:39:50 字數 2652 閱讀 5593

檢查選單項

public class menuitem 

public string getname()

public string getdescription()

public boolean isvegetarian()

public double getprice()

}

lou和mel的選單實現

public class pancakehousemenu 

public void additem(string name,string description,boolean vegetarian,double price)

public arraylist getmenuitems()

}

public class dinermenu 

public void additem(string name,string description,boolean vegetarian,double price)else

} public menuitem getmenuitems()

}

定義迭代器介面

public inte***ce iterator

餐廳實現迭代器介面

public class dinermenuiterator implements iterator 

public boolean hasnext() else

} public object next()

}

煎餅店實現迭代器介面

public class pancakehouseiterator implements iterator

public boolean hasnext() else

} public object next()

}

用迭代器改寫餐廳選單

public class dinermenu 

public void additem(string name,string description,boolean vegetarian,double price)else

} public iterator createiterator()

}

用迭代器改寫煎餅選單

public class pancakehousemenu 

public pancakehousemenu(arraylistpancakeitems)

public void additem(string name,string description,boolean vegetarian,double price)

public iterator createiterator()

}

女招待的實現**

public class waitress 

public void printmenu()

private void printmenu(iterator iterator)

} }

測試迭代器的**

public class menutestdrive 

}

輸出結果:

menu

-----------

breakfast

k&b's pancake breakfast,

2.99,

pancakes with scrambled eggs, and toast,

regular pancake breakfast,

2.99,

pancakes with fried eggs, sausage,

blueberry pancakes,

2.99,

pancakes made with fresh blueberries,

waffles,

2.99,

waffles, with your choice of blueberries or strawberries,

lunch

vegetarian blt,

2.99,

(fakin') bacon with lettuce & tomato on whole wheat,

blt,

2.99,

bacon with lettuce & tomato on whole wheat,

soup of the day,

3.29,

soup of the day ,with a side of potato salad,

hotdog,

3.05,

a hot dog , with saurkraut , relish , onions , topped with cheese,

迭代器模式

迭代器模式 iterator 提供一種方法順序訪問乙個聚合物件中各個元素,而不是暴露該物件的內部表示。乙個聚集物件,而且不管這些物件是什麼都需要遍歷的時候,你就應該考慮用迭代器模式。你需要對聚集有多種方式遍歷時,可以考慮用迭代器模式。為遍歷不同的聚集結構提供如開始,下乙個,是否結束,當前哪一項等統一...

迭代器模式

我最早接觸的設計模式就是迭代器模式了哈 為什麼要有迭代器模式呢?看下下面的 就知道了哈 對於乙個陣列物件sz 我們要怎麼遍歷呢?public void bianlisz class geweishu public myiterator getiterator private class geweis...

迭代器模式

迭代器模式 提供一種方法順序訪問乙個聚合物件中各個元素,而又不暴露該物件多的內部表示。1 iterator抽象類 public abstract class iterator 2 aggregate聚集抽象類 public abstract class aggregate 3 concreteite...