本文共 3537 字,大约阅读时间需要 11 分钟。
例子:菜单合并,第一个菜单采用数组,第二个菜单采用List,第三个菜单采用(key,value),现在服务员需要打印所有菜单上的菜品
解决:让这三个菜单提供一个接口对象(该接口提供访问菜单上的菜品的方法),使用该对象即可访问菜品
数组需要实现Iterator接口,List已经实现,map.values().iterator()
目录结构:
FirstMenu:
public class FirstMenu { private MenuItem[] menu = new MenuItem[3]; private int i = 0; public FirstMenu() { this.addMenuItem(new MenuItem("西瓜", "我是西瓜", 1)); this.addMenuItem(new MenuItem("哈密瓜", "我是哈密西瓜", 2)); this.addMenuItem(new MenuItem("角瓜", "我是角瓜", 3)); } public MenuItem[] getMenu() { return menu; } public void addMenuItem(MenuItem item) { menu[i] = item; i++; } public Iterator getIterator() { return new FistMenuIterator(); } class FistMenuIterator implements Iterator { private int position = 0; @Override public boolean hasNext() { return position < FirstMenu.this.i; } @Override public Object next() { MenuItem item = FirstMenu.this.menu[this.position]; this.position++; return item; } @Override public void remove() { } }}
SecondMenu:
public class SecionMenu { private ArrayList
ThirdMenu:
public class ThirdMenu { private Mapmap = new HashMap (); public ThirdMenu() { map.put("1", new MenuItem("牛肉", "牛肉馅饺子", 20)); map.put("2", new MenuItem("羊肉", "羊肉馅饺子", 30)); map.put("3", new MenuItem("猪肉", "猪肉馅饺子", 10)); } public Iterator getIterator() { return this.map.values().iterator(); }}
菜品实体:MenuItem
public class MenuItem { private String name; private String desc; private int price; public MenuItem(String name, String desc, int price) { this.name = name; this.desc = desc; this.price = price; } public String getName() { return name; } public String getDesc() { return desc; } public int getPrice() { return price; }}
服务员Waitress持有访问菜单聚合实体中每个对象的接口(Iterator)的集合
public class Waitress { private Listlist; public Waitress() { this.list = new ArrayList (); } public void addMenu(Iterator menu) { this.list.add(menu); } public void printAllMenu() { for (Iterator iterator : list) { System.out.println("-----------------------------"); while (iterator.hasNext()) { MenuItem item = (MenuItem) iterator.next(); System.out.println(item.getName() + ":" + item.getDesc() + ":" + item.getPrice()); } System.out.println("-----------------------------"); } }}
测试类Main:
public class Main { public static void main(String[] args) { FirstMenu firstMenu = new FirstMenu(); SecionMenu secionMenu = new SecionMenu(); ThirdMenu thirdMenu = new ThirdMenu(); Waitress waitress = new Waitress(); waitress.addMenu(firstMenu.getIterator()); waitress.addMenu(secionMenu.getIterator()); waitress.addMenu(thirdMenu.getIterator()); waitress.printAllMenu(); }}
输出结果:
总结: 面向接口编程,接口中提供访问对象的方法(对对象的一系列动作),想对对象做某些更改或者查询时直接向外暴露接口即可。
转载地址:http://nszfa.baihongyu.com/