迭代器模式定义:提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露对象的具体细节。
实现:
假设,有个菜单,里面包含菜单项,如下
- package com.zlh.iterator;
- public class BreakfastMenu {
- private MenuItem[] items;
- public MenuItem[] getItems() {
- return items;
- }
- public void setItems(MenuItem[] items) {
- this.items = items;
- }
- public BreakfastMenu() {
- items = new MenuItem[5];
- items[0] = new MenuItem("1",1);
- items[1] = new MenuItem("2",2);
- items[2] = new MenuItem("3",3);
- items[3] = new MenuItem("4",4);
- items[4] = new MenuItem("5",5);
- }
- public Iterator createIterator(){
- return new BreakFastIterator(items);
- }
- }
其中,菜单项menuItem如下:
- package com.zlh.iterator;
- public class MenuItem {
- private String name;
- private double price;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public double getPrice() {
- return price;
- }
- public void setPrice(double price) {
- this.price = price;
- }
- public MenuItem(String name, double price) {
- this.name = name;
- this.price = price;
- }
- }
BreakfastMenu 有一个函数,主要是生成菜单项的迭代器,createIterator()。
根据“围绕接口编程原则”,编写了早餐菜单迭代器
- package com.zlh.iterator;
- public interface Iterator {
- boolean hasNext();
- Object next();
- void remove();
- }
- package com.zlh.iterator;
- public class BreakFastIterator implements Iterator {
- private MenuItem[] items;
- private int position;
- public BreakFastIterator(MenuItem[] items) {
- this.items = items;
- this.position = 0;
- }
- public boolean hasNext() {
- if (position < items.length && items[position]!=null)
- return true;
- else
- return false;
- }
- public Object next() {
- MenuItem menuitem = items[position];
- position++;
- return menuitem;
- }
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
这样,以数组为菜单项存储形式的早餐菜单,就可以实现类似集合形式的迭代器访问了。由于数组不可删除,故remove()方法抛出UnsupportedOperationException异常。
下面是相应的测试类,服务员可以根据早餐,也可以根据以ArrayList形存储的中餐来传菜了。
- package com.zlh.iterator;
- public class Waitress {
- private BreakfastMenu breakfastMenu;
- public BreakfastMenu getBreakfastMenu() {
- return breakfastMenu;
- }
- public void setBreakfastMenu(BreakfastMenu breakfastMenu) {
- this.breakfastMenu = breakfastMenu;
- }
- public Waitress(BreakfastMenu breakfastMenu) {
- this.breakfastMenu = breakfastMenu;
- }
- public void printMenu(Iterator iterator){
- while(iterator.hasNext()){
- MenuItem menuItem = (MenuItem) iterator.next();
- System.out.println("menu name: "+menuItem.getName());
- System.out.println("menu price:" + menuItem.getPrice());
- }
- }
- }
- package com.zlh.iterator;
- public class TestDriver {
- public static void main(String[] args) {
- BreakfastMenu breakfastMenu = new BreakfastMenu();
- Waitress waitress = new Waitress(breakfastMenu);
- Iterator iterator = breakfastMenu.createIterator();
- waitress.printMenu(iterator);
- }
- }