HeadFirst设计模式-迭代器模式和组合模式

迭代器模式:

让用户通过特定的接口访问容器的数据,不需要了解容器内部的数据结构。
比如menu里有早餐的Array和完成的ArrayList,遍历时需要用分别用遍历数组和ArrayList(遍历两次),且如果增加甜品的HashMap时需要修改menu的代码。
可以让数组,ArrayList和HashMap等实现迭代器接口,在menu里设置迭代器的数组或list,通过迭代器遍历一次即可(可简写成for in遍历)。

组合模式:

DrinkComponent 里默认的方法实现时直接报错,因为DrinkMenu需要实现addChild(需要重写),而DrinkItem不应该有这个方法。所以让DrinkItem调用addChild时报错是很好的解决方案。

public abstract class DrinkComponent {
    public void getNames(String prefix) {
        throw new UnsupportedOperationException();
    }

    public void addChild(DrinkComponent d){
        throw new UnsupportedOperationException();
    }
}
public class DrinkMenu extends DrinkComponent{
    private String name;
    private List<DrinkComponent> drinkComponents=new ArrayList<>();

    public DrinkMenu(String name) {
        this.name = name;
    }

    @Override
    public void getNames(String prefix) {
        System.out.println(prefix+">"+name);
        for(DrinkComponent dc:drinkComponents){
            dc.getNames("--"+prefix);
        }
    }
    @Override
    public void addChild(DrinkComponent d) {
        drinkComponents.add(d);
    }
}
public class DrinkItem extends DrinkComponent{
    private String name;

    public DrinkItem(String name) {
        this.name = name;
    }

    @Override
    public void getNames(String prefix) {
        System.out.println(prefix+">"+name);
    }
}
public class Testt {
    @Test
    public void oo(){
        DrinkComponent coffeeMenu=new DrinkMenu("coffeeMenu");
        DrinkComponent cocoa=new DrinkMenu("cocoa");
        DrinkComponent hotCocoa=new DrinkItem("hotCocoa");
        DrinkComponent hotoCocoa=new DrinkItem("hotoCocoa");
        DrinkComponent chino=new DrinkMenu("chino");
        cocoa.addChild(hotCocoa);
        cocoa.addChild(hotoCocoa);
        coffeeMenu.addChild(cocoa);
        coffeeMenu.addChild(chino);

        DrinkComponent teaMenu=new DrinkMenu("teaMenu");

        DrinkComponent menu=new DrinkMenu("menu");
        menu.addChild(coffeeMenu);
        menu.addChild(teaMenu);
        menu.getNames("");
        /*
        >menu
        -->coffeeMenu
        ---->cocoa
        ------>hotCocoa
        ------>hotoCocoa
        ---->chino
        -->teaMenu*/
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值