码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式 - 迭代器模式(iterator pattern) Java 迭代器(Iterator) 详解

时间:2014-06-27 23:26:42      阅读:323      评论:0      收藏:0      [点我收藏+]

标签:mystra   设计模式   迭代器   java迭代器   代码   

迭代器模式(iterator pattern) Java 迭代器(Iterator) 详解


本文地址: http://blog.csdn.net/caroline_wendy


参考迭代器模式(iterator pattern): http://blog.csdn.net/caroline_wendy/article/details/35254643


Java的标准库(util)中包含迭代器接口(iterator interface), import java.util.Iterator;

继承(implements)迭代器接口(Iterator)需要重写(override)三个函数: hasNext(), next()和remove();

Java的聚合类型, 如ArrayList包含迭代器.

但是数组类型, 需要重写相应的迭代器(iterator).


具体方法:

1. ArrayList类型, 包含迭代器的方法, 可以直接返回.

/**
 * @time 2014年6月20日
 */
package iterator;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @author C.L.Wang
 *
 */
public class PancakeHouseMenu implements Menu {

	ArrayList<MenuItem> menuItems;
	
	/**
	 * 
	 */
	public PancakeHouseMenu() {
		// TODO Auto-generated constructor stub
		menuItems = new ArrayList<MenuItem>();
		
		addItem("K&B‘s 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 Pancakes", 
				"Pancakes made with fresh blueberries", true, 3.49);
		
		addItem("Waffles",
				"Waffles, with your choice of blueberries or strawberries", true, 3.59);
	}
	
	public void addItem(String name, String description,
			boolean vegetarian, double price) {
		MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
		menuItems.add(menuItem);
	}

	public Iterator<MenuItem> createIterator() {
		return menuItems.iterator();
	}
	
}

2. 数组类型, 创建相应的迭代器类, 继承(implements)迭代器(Iterator), 重写迭代器的方法.

/**
 * @time 2014年6月26日
 */
package iterator;

import java.util.Iterator;

/**
 * @author C.L.Wang
 *
 */
public class DinerMenu implements Menu {

	static final int MAX_ITEMS = 6;
	int numberOfItems = 0;
	MenuItem[] menuItems;
	
	/**
	 * 
	 */
	public DinerMenu() {
		// TODO Auto-generated constructor stub
		
		menuItems = new MenuItem[MAX_ITEMS];
		
		addItem("Vegetarian BLT", 
				"(Fakin‘) Bacon with lettuce & tomato on whole wheat", true, 2.99);
		
		addItem("BLT", 
				"Bacon with lettuce & tomato on the whole wheat", false, 2.99);
		
		addItem("Soup of the day", 
				"Soup of the day, with a side of potato salad", false, 3.29);
		
		addItem("Hotdog", 
				"A hot dog, with saurkraut, relish, onions, topped with cheese", false, 3.05);
		
	}
	
	public void addItem(String name, String description,
			boolean vegetarian, double price) {
		MenuItem menuItem = 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] = menuItem;
			++numberOfItems;
		}
	}

	public Iterator<MenuItem> createIterator() {
		return new DinerMenuIterator(menuItems);
	}
	
}


/**
 * @time 2014年6月27日
 */
package iterator;

import java.util.Iterator;

/**
 * @author C.L.Wang
 *
 */
public class DinerMenuIterator implements Iterator<MenuItem> {

	MenuItem[] items;
	int position = 0;
	
	/**
	 * 
	 */
	public DinerMenuIterator(MenuItem[] items) {
		// TODO Auto-generated constructor stub
		this.items = items;
	}

	/* (non-Javadoc)
	 * @see iterator.Iterator#hasNext()
	 */
	@Override
	public boolean hasNext() {
		// TODO Auto-generated method stub
		
		if (position >= items.length || items[position] == null) {
			return false;
		}
		
		return true;
	}

	/* (non-Javadoc)
	 * @see iterator.Iterator#next()
	 */
	@Override
	public MenuItem next() {
		// TODO Auto-generated method stub
		
		MenuItem menuItem = items[position];
		++position;
		
		return menuItem;
	}

	@Override
	public void remove() {
		if (position <= 0) {
			throw new IllegalStateException
			("You can‘t remove an item until you‘ve done at least one next()");
		}
		
		if (items[position-1] != null) {
			for (int i=position-1; i<(items.length-1); ++i) {
				items[i] = items[i+1];
			}
			items[items.length-1] = null;
		}
	}
	
}

3. 菜单接口(interface), 包含创建迭代器(createIterator)的方法.

/**
 * @time 2014年6月27日
 */
package iterator;

import java.util.Iterator;

/**
 * @author C.L.Wang
 *
 */
public interface Menu {
	public Iterator<MenuItem> createIterator();
}

4. 具体的菜单项, ArrayList和数组的基本元素.

/**
 * @time 2014年6月20日
 */
package iterator;

/**
 * @author C.L.Wang
 *
 */
public class MenuItem {

	String name;
	String description;
	boolean vegetarian; //是否是素食
	double price;
	
	/**
	 * 
	 */
	public MenuItem(String name, 
			String description, 
			boolean vegetarian, 
			double price) 
	{
		// TODO Auto-generated constructor stub
		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;
	}
	
}

5. 客户类(client), 调用迭代器(iterator)方法.

/**
 * @time 2014年6月27日
 */
package iterator;

import java.util.Iterator;

/**
 * @author C.L.Wang
 *
 */
public class Waitress {

	Menu pancakeHouseMenu;
	Menu dinerMenu;
	
	/**
	 * 
	 */
	public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) {
		// TODO Auto-generated constructor stub
		this.pancakeHouseMenu = pancakeHouseMenu;
		this.dinerMenu = dinerMenu;
	}
	
	public void printMenu() {
		Iterator<MenuItem> pancakeIterator = pancakeHouseMenu.createIterator();
		Iterator<MenuItem> dinerIterator = dinerMenu.createIterator();
		System.out.println("MENU\n----\nBREAKFAST");
		printMenu(pancakeIterator);
		System.out.println("\nLUNCH");
		printMenu(dinerIterator);
		
	}
	
	private void printMenu(Iterator<MenuItem> iterator) {
		while (iterator.hasNext()) {
			MenuItem menuItem = (MenuItem)iterator.next();
			System.out.print(menuItem.getName() + ": ");
			System.out.print(menuItem.getPrice() + " -- ");
			System.out.println(menuItem.getDescription());
		}
	}

}

6. 测试:

/**
 * @time 2014年6月27日
 */
package iterator;

/**
 * @author C.L.Wang
 *
 */
public class MenuTestDrive {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
		DinerMenu dinerMenu = new DinerMenu();
		
		Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);
		
		waitress.printMenu();
	}

}

7. 输出:

MENU
----
BREAKFAST
K&B‘s Pancake Breakfast: 2.99 -- Pancakes with scrambled eggs, and toast
Regular Pancake Breakfast: 2.99 -- Pancakes with fried eggs, sausage
Blueberry Pancakes: 3.49 -- Pancakes made with fresh blueberries
Waffles: 3.59 -- Waffles, with your choice of blueberries or strawberries

LUNCH
Vegetarian BLT: 2.99 -- (Fakin‘) Bacon with lettuce & tomato on whole wheat
BLT: 2.99 -- Bacon with lettuce & tomato on the whole wheat
Soup of the day: 3.29 -- Soup of the day, with a side of potato salad
Hotdog: 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese




bubuko.com,布布扣





设计模式 - 迭代器模式(iterator pattern) Java 迭代器(Iterator) 详解,布布扣,bubuko.com

设计模式 - 迭代器模式(iterator pattern) Java 迭代器(Iterator) 详解

标签:mystra   设计模式   迭代器   java迭代器   代码   

原文地址:http://blog.csdn.net/caroline_wendy/article/details/35268931

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!