設計模式 - 迭代模式(iterator pattern) Java 迭代器(Iterator) 詳細解釋

來源:互聯網
上載者:User

標籤:

迭代模式(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 stubmenuItems = 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 stubmenuItems = 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 stubthis.items = items;}/* (non-Javadoc) * @see iterator.Iterator#hasNext() */@Overridepublic boolean hasNext() {// TODO Auto-generated method stubif (position >= items.length || items[position] == null) {return false;}return true;}/* (non-Javadoc) * @see iterator.Iterator#next() */@Overridepublic MenuItem next() {// TODO Auto-generated method stubMenuItem menuItem = items[position];++position;return menuItem;}@Overridepublic 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 stubthis.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 stubthis.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 stubPancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();DinerMenu dinerMenu = new DinerMenu();Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu);waitress.printMenu();}}

7. 輸出:

MENU----BREAKFASTK&B‘s Pancake Breakfast: 2.99 -- Pancakes with scrambled eggs, and toastRegular Pancake Breakfast: 2.99 -- Pancakes with fried eggs, sausageBlueberry Pancakes: 3.49 -- Pancakes made with fresh blueberriesWaffles: 3.59 -- Waffles, with your choice of blueberries or strawberriesLUNCHVegetarian BLT: 2.99 -- (Fakin‘) Bacon with lettuce & tomato on whole wheatBLT: 2.99 -- Bacon with lettuce & tomato on the whole wheatSoup of the day: 3.29 -- Soup of the day, with a side of potato saladHotdog: 3.05 -- A hot dog, with saurkraut, relish, onions, topped with cheese









著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。

設計模式 - 迭代模式(iterator pattern) Java 迭代器(Iterator) 詳細解釋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.