设计模式随笔-迭代器与组合模式

迭代器与组合模式

有很多方法可以把对象聚合起来,比如用数组、堆栈、列表或者散列表,各有各的好处。有时候你需要遍历这些对象,而当遍历对象时,你真的想把遍历的代码展示给用户看吗?这样太不专业了。而且每种聚合方式可能遍历的算法都不一样,有没有什么方法可以统一他们的遍历模式呢?可能迭代器模式是一个不错的选择。

迭代器模式

现在有两个餐厅需要合并了。一个是早餐的餐厅,一个是午餐的餐厅,他们都同意用统一的菜单项

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 boolean isVegetarian() {
        return vegetarian;
    }

    public double getPrice() {
        return price;
    }
}

但是早餐店的老板用了用了集合(List)来形成菜单的,代码如下:

public class PancakeHouseMenu {
    List<MenuItem> menuItems;

    public PancakeHouseMenu() {
        menuItems = new ArrayList<MenuItem>();

        addItem("K&Bs Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99);

        addItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99);

        addItem("Blueberry Pancake", "Pancakes made with fresh blueberries", true, 3.49);

        addItem("Waffles", "Waffles, with your choise of blueberries or strawberries", true, 3.59);
    }

    public void addItem(String name, String description, boolean vegetarian, double price){
        MenuItem item = new MenuItem(name, description, vegetarian, price);
        menuItems.add(item);
    }

    public List<MenuItem> getMenuItems() {
        return menuItems;
    }

}

而午餐店的老板是用了数组(MenuItem[])来形成菜单的,代码如下:

public class DinerMenu  {
    static final int MAX_ITEMS = 6;
    int numberOfItems = 0;
    MenuItem[] menuItems;

    public DinerMenu() {
        menuItems = new MenuItem[MAX_ITEMS];

        addItem("Vegetarian BLT", "Bacon with lettuce & tomato on whole wheat", true, 2.99);

        addItem("Vegetarian BLT", "Bacon with lettuce & tomato on whole wheat", true, 2.99);

        addItem("Soup of the day", "Soup of the day, with a side of potato salaed", false, 3.29);
    }

    public void addItem(String name, String description, boolean vegetarian, double price){
        MenuItem item = new MenuItem(name, description, vegetarian, price);
        if (numberOfItems >= MAX_ITEMS){
            System.err.println("Sorry, menu is full! Can't add item to menu");
        }else {
            menuItems[numberOfItems] = item;
            numberOfItems++;
        }
    }

    public MenuItem[] getMenuItems() {
        return menuItems;
    }
}

现在有一个招待员爱丽丝做这两个餐厅的招待员,她的功能有展示所有的菜单,展示早餐的菜单和展示午餐的菜单等。服务员爱丽丝的代码如下:

public class Waiter {
    PancakeHouseMenu houseMenu = new PancakeHouseMenu();
    List<MenuItem> houseMenuList = houseMenu.getMenuItems();
    DinerMenu dinerMenu = new DinerMenu();
    MenuItem[] dinerMenuList = dinerMenu.getMenuItems();

    //打印菜单的每一项
    public void printMenu(){

        for (int i=0; i<houseMenuList.size(); i++){
            MenuItem item = houseMenuList.get(i);
            System.out.print(item.getName() + " ");
            System.out.println(item.getPrice() + " ");
            System.out.println(item.getDescription());
        }

        for (int i=0; i<dinerMenuList.length; i++){
            MenuItem item = dinerMenuList[i];
            System.out.print(item.getName() + " ");
            System.out.println(item.getPrice() + " ");
            System.out.println(item.getDescription());
        }
    }

    //打印早餐项
    public void printBreakfastMenu(){
        for (int i=0; i<houseMenuList.size(); i++){
            MenuItem item = houseMenuList.get(i);
            System.out.print(item.getName() + " ");
            System.out.println(item.getPrice() + " ");
            System.out.println(item.getDescription());
        }
    }

    //打印午餐项
    public void printLunchDiner(){
        for (int i=0; i<dinerMenuList.length; i++){
            MenuItem item = dinerMenuList[i];
            System.out.print(item.getName() + " ");
            System.out.println(item.getPrice() + " ");
            System.out.println(item.getDescription());
        }
    }
}

但是因为早餐店和午餐店用的聚合类型不同,服务员爱丽丝总是需要两个循环遍历这些项目。如果来了第三个餐馆店,那么就需要三个遍历了,我的天,如果在有更多,代码不可想象了。
于是我们需要一个能够适合所有聚合类型的方法来完成统一的遍历。
下面我们来分析一下早餐项和午餐项是如何遍历的:
早餐项遍历:
集合遍历
午餐项遍历:
数组遍历
于是我们要创建一个迭代器,来统一他们的遍历过程。
JDK的util包里有一个Iterator,就是聚合类型的一个迭代器接口了。具体大家可以查看下java.util.Iterator

public interface Iterator<E> {
    boolean hasNext();

    E next();

    void remove();
}

这个接口就三个方法,hasNext()告诉我们这个聚合中是否还有更多的元素、next()返回这个聚合元素的下一个对象、remove()移除聚合中的当前对象。
但是我们知道数组没有自带iterator方法的,所以我们需要自己添加一个iterator的数组实现。代码如下:

public class DinerMenuIterator implements Iterator{
    MenuItem[] item;
    int position = 0;

    public DinerMenuIterator(MenuItem[] item) {
        this.item = item;
    }

    public boolean hasNext() {
        if (position < item.length && item[position] != null){
            return true;
        }
        return false;
    }

    public Object next() {
        MenuItem object = item[position];
        position++;
        return object;
    }

    public void remove() {
        throw new UnsupportedOperationException("不支持的方法");
    }
}

因为remove方法对于我们是没有用处的,所以我们可以抛一个异常。
* @throws UnsupportedOperationException if the {@code remove}
* operation is not supported by this iterator

于是现在的服务员爱丽丝可以根据迭代器来遍历菜单了,简单又方便:

public class Waitress {
    private DinerMenu dinerMenu;

    private PancakeHouseMenu houseMenu;

    public Waitress(DinerMenu dinerMenu, PancakeHouseMenu houseMenu) {
        this.dinerMenu = dinerMenu;
        this.houseMenu = houseMenu;
    }

    public void printMenu(){
        Iterator iterator1 = dinerMenu.createIterator();
        Iterator iterator2 = houseMenu.createIterator();
        System.out.println("###########################");
        printMenu(iterator1);
        printMenu(iterator2);
        System.out.println("###########################");
    }

    private void printMenu(Iterator iterator){
        while (iterator.hasNext()){
            MenuItem item = (MenuItem) iterator.next();
            System.out.print(item.getName() + " ");
            System.out.println(item.getPrice() + " ");
            System.out.println(item.getDescription());
        }
    }
}

迭代器模式:提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露其内部的表示。

单一责任:如果我们允许在聚合实现他们内部的集合,而且还要实现相关操作和遍历操作。这样的代码是好还是不好呢?
我们知道,当我们允许类不但要完成自己的某种操作(管理某种聚合),而且还有负担更多的责任(例如遍历)。我们就给这个类两个变化的原因。这样变化又成为我们的话题了

单一责任原则:一个类只有一个引起变化的原因。

当然在java5的时候java出了一个功能for/in功能,可以用for循环顺序的遍历一个聚合对象。
for(Object obj : Conllection);大家也可以用这种方法尝试一下哈。

加入子菜单(组合模式)

需求:现在我们要丰富我们的菜单了,需要在午餐店里面添加甜点菜单了,所谓的甜点菜单可以理解为菜单里面的菜单。就是所谓的子菜单了。
所谓的组合模式,就是把菜单和菜单项当做一个大菜单,然后把菜单和子菜单都弄成大菜单的模式,形成树形结构。
首先我们构建一个大菜单的抽象类,用于给菜单和菜单项继承用的

public abstract class MenuComponent {
    public void add(MenuComponent menuComponent){
        throw new UnsupportedOperationException();
    }

    public void remove(MenuComponent menuComponent){
        throw new UnsupportedOperationException();
    }

    public MenuComponent getChild(int i){
        throw new UnsupportedOperationException();
    }

    public String getName(){
        throw new UnsupportedOperationException();
    }

    public String getDescription(){
        throw new UnsupportedOperationException();
    }

    public double getPrice(){
        throw new UnsupportedOperationException();
    }

    public boolean isVegetarian(){
        throw new UnsupportedOperationException();
    }

    public void print(){
        throw new UnsupportedOperationException();
    }

    public Iterator createIterator(){
        throw new UnsupportedOperationException();
    }
}

MenuComponent 定义了菜单和菜单项要用到的方法。这是组合模式的一个特点。
然后我们定义菜单项代码:

public class MenuItem extends MenuComponent {
    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;
    }

    @Override
    public String getName() {
        return name;
    }
    @Override
    public String getDescription() {
        return description;
    }
    @Override
    public boolean isVegetarian() {
        return vegetarian;
    }
    @Override
    public double getPrice() {
        return price;
    }
    @Override
    public void print(){
        System.out.println(toString());
    }
    @Override
    public String toString() {
        return "MenuItem{" +
                "name='" + name + '\'' +
                ", description='" + description + '\'' +
                ", vegetarian=" + vegetarian +
                ", price=" + price +
                '}';
    }

    @Override
    public Iterator createIterator() {
        return new NullIterator();
    }
}

然后是菜单的代码:

public class Menu extends MenuComponent {
    List<MenuComponent> menuComponents = new ArrayList<MenuComponent>();
    String name;
    String description;

    public Menu(String name, String description) {
        this.name = name;
        this.description = description;
    }

    @Override
    public void add(MenuComponent menuComponent) {
        menuComponents.add(menuComponent);
    }

    @Override
    public void remove(MenuComponent menuComponent) {
        menuComponents.remove(menuComponent);
    }

    @Override
    public MenuComponent getChild(int i) {
        return menuComponents.get(i);
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public Iterator createIterator() {
        return new CompositeIterator(menuComponents.iterator());
    }

    @Override
    public void print() {
        System.out.println("name ="+name);
        System.out.println("description ="+description);
        Iterator<MenuComponent> it = menuComponents.iterator();
        while (it.hasNext()){
            MenuComponent temp = it.next();
            temp.print();
        }
    }
}

然后是新的服务员爱丽丝的代码:

public class Waitress {
    MenuComponent allMenu;

    public Waitress(MenuComponent allMenu) {
        this.allMenu = allMenu;
    }

    public void print(){
        allMenu.print();
    }
}

但是上面的服务员是没有实现迭代器的,如果要实现迭代器的话,就需要一个组合迭代器了。
该迭代器用了递归的方式,可能有点难以理解,记住“递归使我们最好的朋友哦”。

public class CompositeIterator implements Iterator {

    Stack<Iterator> stack = new Stack<Iterator>();

    public CompositeIterator(Iterator<MenuComponent> iterator) {
        stack.push(iterator);
    }

    public boolean hasNext() {
        if (stack.isEmpty()){
            return false;
        }else{
            Iterator iterator = stack.peek();
            if (!iterator.hasNext()){
                stack.pop();
                return hasNext();
            } else {
                return true;
            }
        }
    }

    public Object next() {
        if (hasNext()){
            Iterator<MenuComponent> iterator = stack.peek();
            MenuComponent component = iterator.next();
            if (component instanceof Menu){
                stack.push(component.createIterator());
            }
            return component;
        }else {
            return null;
        }
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

然后服务员加入一个打印素食菜单的方法:

public void printVegetarianMenu(){
        Iterator iterator = allMenu.createIterator();
        System.out.println("VEGETARIAN MENU");
        while(iterator.hasNext()){
            MenuComponent menuComponent = (MenuComponent) iterator.next();
            try{
                if (menuComponent.isVegetarian()){
                    menuComponent.print();
                }
            }catch (Exception e){

            }
        }
    }

//测试服务员
public static void main(String[] args) {
        Waitress waitress = new Waitress(new Menu("all Menu", "All menu parent"));
        MenuComponent pancakeHouseMenu = new Menu("PANCAKE HOUSE MENU", "breakfast");
        MenuComponent dinerMenu = new Menu("DINER MENU", "diner");
        MenuComponent dessertMenu = new Menu("DESSERT MENU", "dessert");

        waitress.allMenu.add(pancakeHouseMenu);
        waitress.allMenu.add(dinerMenu);

        pancakeHouseMenu.add(new MenuItem("K&Bs Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99));
        pancakeHouseMenu.add(new MenuItem("Regular Pancake Breakfast", "Pancakes with fried eggs, sausage", false, 2.99));
        pancakeHouseMenu.add(new MenuItem("Blueberry Pancake", "Pancakes made with fresh blueberries", true, 3.49));
        pancakeHouseMenu.add(new MenuItem("Waffles", "Waffles, with your choise of blueberries or strawberries", true, 3.59));

        dinerMenu.add(new MenuItem("Vegetarian BLT", "Bacon with lettuce & tomato on whole wheat", true, 2.99));
        dinerMenu.add(new MenuItem("Soup of the day", "Soup of the day, with a side of potato salaed", false, 3.29));

        dessertMenu.add(new MenuItem("Cute Pie", "Soup of the day, with a side of potato salaed", false, 3.89));
        dinerMenu.add(dessertMenu);

        waitress.print();
        waitress.printVegetarianMenu();

    }

组合模式:允许你将对象组合成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象组合。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值