设计模式之迭代器与组合模式

有许多中方法可以把对象堆起来成为一个集合(Collection)。你可以把他们放进数组,堆栈,列表或散列表(Hashtable)中,这是你的自由。每一种都有他自己的优点和合适的使用时机,但总有一个时候,你的客户想要遍历这些对象,而当他这么做时,你打算让客户看到你的实现吗?我们当然希望最好不要!这太不专业了。没关系,不要为你等工作担心,你将在这章学习如何能让客户遍历你的对象而又无法窥视你存储对象的方式,也将学习如何创建一些对象超集合(super collection)。

爆炸性新闻:对象村餐厅和对象村煎饼屋合并了。

真是个好消息,现在我们可以再同一个地方,想用煎饼屋美味的煎饼早餐,和好吃的餐厅午餐,但是,好像有点麻烦

煎饼屋使用ArrayList记录他的菜单项
餐厅使用数组记录菜单项

检查菜单项

public class MenuItem {
    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 double getPrice() {
        return price;
    }
  
    public boolean isVegetarian() {
        return vegetarian;
    }
}

餐厅和煎饼屋的菜单实现:

煎饼屋使用的是ArrayList保存菜单项。

原文地址:https://www.cnblogs.com/youxin/p/2713004.html