设计模式:生活中的迭代器模式
// 迭代器接口
interface Iterator<T> {
boolean hasNext();
T next();
}
// 菜单项
class MenuItem {
private String name;
private double price;
public MenuItem(String name, double price) {
this.name = name;
this.price = price;
}
// Getter and setter methods...
}
// 菜单聚合接口
interface Menu {
Iterator<MenuItem> createIterator();
}
// 具体的菜单类
class DinnerMenu implements Menu {
private List<MenuItem> menuItems;
public DinnerMenu() {
menuItems = new ArrayList<>();
// 添加一些菜品到菜单
addItem("Vegetarian BLT", 2.99);
addItem("BLT", 2.99);
addItem("Soup of the day", 3.29);
// 更多菜品...
}
public void addItem(String name, double price) {
MenuItem menuItem = new MenuItem(name, price);
menuItems.add(menuItem);
}
@Override
public Iterator<MenuItem> createIterator() {
return menuItems.iterator(); // 利用 Java 内置的迭代器
}
}
// 客户端代码
public class MenuTestDrive {
public static void main(String[] args) {
Menu dinnerMenu = new DinnerMenu();
Iterator<MenuItem> iterator = dinnerMenu.createIterator();
while (iterator.hasNext()) {
MenuItem item = iterator.next();
System.out.println(item.getName() + ", $" + item.getPrice());
}
}
}