一、

1.迭代器模式是对遍历集合元素的抽象

2.The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

3.

二、

1.

package headfirst.designpatterns.iterator.dinermerger;

public interface Iterator {
boolean hasNext();
MenuItem next();
}

2.

 package headfirst.designpatterns.iterator.dinermerger;

 public class DinerMenuIterator implements Iterator {
MenuItem[] items;
int position = 0; public DinerMenuIterator(MenuItem[] items) {
this.items = items;
} public MenuItem next() {
MenuItem menuItem = items[position];
position = position + 1;
return menuItem;
} public boolean hasNext() {
if (position >= items.length || items[position] == null) {
return false;
} else {
return true;
}
}
}

3.

 package headfirst.designpatterns.iterator.dinermerger;

 import java.util.ArrayList;

 public class PancakeHouseMenuIterator implements Iterator {
ArrayList<MenuItem> items;
int position = 0; public PancakeHouseMenuIterator(ArrayList<MenuItem> items) {
this.items = items;
} public MenuItem next() {
MenuItem item = items.get(position);
position = position + 1;
return item;
} public boolean hasNext() {
if (position >= items.size()) {
return false;
} else {
return true;
}
}
}

4.

 package headfirst.designpatterns.iterator.dinermerger;

 public class DinerMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems; public DinerMenu() {
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 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);
addItem("Steamed Veggies and Brown Rice",
"Steamed vegetables over brown rice", true, 3.99);
addItem("Pasta",
"Spaghetti with Marinara Sauce, and a slice of sourdough bread",
true, 3.89);
} 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 = numberOfItems + 1;
}
} public MenuItem[] getMenuItems() {
return menuItems;
} public Iterator createIterator() {
return new DinerMenuIterator(menuItems);
// To test Alternating menu items, comment out above line,
// and uncomment the line below.
//return new AlternatingDinerMenuIterator(menuItems);
} // other menu methods here
}

5.

 package headfirst.designpatterns.iterator.dinermerger;

 import java.util.ArrayList;

 public class PancakeHouseMenu implements Menu {
ArrayList<MenuItem> menuItems; public PancakeHouseMenu() {
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 ArrayList<MenuItem> getMenuItems() {
return menuItems;
} public Iterator createIterator() {
return new PancakeHouseMenuIterator(menuItems);
} public String toString() {
return "Objectville Pancake House Menu";
} // other menu methods here
}

6.

 package headfirst.designpatterns.iterator.dinermerger;

 public interface Menu {
public Iterator createIterator();
}

7.

 package headfirst.designpatterns.iterator.dinermerger;

 public class MenuItem {
String name;
String description;
boolean vegetarian;
double price; public MenuItem(String name,
String description,
boolean vegetarian,
double price)
{
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;
}
public String toString() {
return (name + ", $" + price + "\n " + description);
}
}

8.

 package headfirst.designpatterns.iterator.dinermerger;

 public class Waitress {
Menu pancakeHouseMenu;
Menu dinerMenu; public Waitress(Menu pancakeHouseMenu, Menu dinerMenu) {
this.pancakeHouseMenu = pancakeHouseMenu;
this.dinerMenu = dinerMenu;
} public void printMenu() {
Iterator pancakeIterator = pancakeHouseMenu.createIterator();
Iterator dinerIterator = dinerMenu.createIterator(); System.out.println("MENU\n----\nBREAKFAST");
printMenu(pancakeIterator);
System.out.println("\nLUNCH");
printMenu(dinerIterator); } private void printMenu(Iterator iterator) {
while (iterator.hasNext()) {
MenuItem menuItem = iterator.next();
System.out.print(menuItem.getName() + ", ");
System.out.print(menuItem.getPrice() + " -- ");
System.out.println(menuItem.getDescription());
}
} public void printVegetarianMenu() {
printVegetarianMenu(pancakeHouseMenu.createIterator());
printVegetarianMenu(dinerMenu.createIterator());
} public boolean isItemVegetarian(String name) {
Iterator breakfastIterator = pancakeHouseMenu.createIterator();
if (isVegetarian(name, breakfastIterator)) {
return true;
}
Iterator dinnerIterator = dinerMenu.createIterator();
if (isVegetarian(name, dinnerIterator)) {
return true;
}
return false;
} private void printVegetarianMenu(Iterator iterator) {
while (iterator.hasNext()) {
MenuItem menuItem = iterator.next();
if (menuItem.isVegetarian()) {
System.out.print(menuItem.getName());
System.out.println("\t\t" + menuItem.getPrice());
System.out.println("\t" + menuItem.getDescription());
}
}
} private boolean isVegetarian(String name, Iterator iterator) {
while (iterator.hasNext()) {
MenuItem menuItem = iterator.next();
if (menuItem.getName().equals(name)) {
if (menuItem.isVegetarian()) {
return true;
}
}
}
return false;
}
}

9.

 package headfirst.designpatterns.iterator.dinermerger;

 import java.util.*;

 public class MenuTestDrive {
public static void main(String args[]) {
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu(); Waitress waitress = new Waitress(pancakeHouseMenu, dinerMenu); // Without iterators
//printMenu(); // With iterators
waitress.printMenu(); } /*
* Without the Waitress, we need the code below...
*/
public static void printMenu() {
PancakeHouseMenu pancakeHouseMenu = new PancakeHouseMenu();
DinerMenu dinerMenu = new DinerMenu(); ArrayList<MenuItem> breakfastItems = pancakeHouseMenu.getMenuItems();
MenuItem[] lunchItems = dinerMenu.getMenuItems(); // Hiding implementation
System.out.println("USING FOR EACH");
for (MenuItem menuItem : breakfastItems) {
System.out.print(menuItem.getName());
System.out.println("\t\t" + menuItem.getPrice());
System.out.println("\t" + menuItem.getDescription());
}
for (MenuItem menuItem : lunchItems) {
System.out.print(menuItem.getName());
System.out.println("\t\t" + menuItem.getPrice());
System.out.println("\t" + menuItem.getDescription());
} // Exposing implementation
System.out.println("USING FOR LOOPS");
for (int i = 0; i < breakfastItems.size(); i++) {
MenuItem menuItem = (MenuItem)breakfastItems.get(i);
System.out.print(menuItem.getName());
System.out.println("\t\t" + menuItem.getPrice());
System.out.println("\t" + menuItem.getDescription());
} for (int i = 0; i < lunchItems.length; i++) {
MenuItem menuItem = lunchItems[i];
System.out.print(menuItem.getName());
System.out.println("\t\t" + menuItem.getPrice());
System.out.println("\t" + menuItem.getDescription());
}
}
}

三、用java.util.Iterator

1.

 package headfirst.designpatterns.iterator.dinermergercafe;

 import java.util.Iterator;

 public class DinerMenuIterator implements Iterator<MenuItem> {
MenuItem[] list;
int position = 0; public DinerMenuIterator(MenuItem[] list) {
this.list = list;
} public MenuItem next() {
MenuItem menuItem = list[position];
position = position + 1;
return menuItem;
} public boolean hasNext() {
if (position >= list.length || list[position] == null) {
return false;
} else {
return true;
}
} public void remove() {
if (position <= 0) {
throw new IllegalStateException
("You can't remove an item until you've done at least one next()");
}
if (list[position-1] != null) {
for (int i = position-1; i < (list.length-1); i++) {
list[i] = list[i+1];
}
list[list.length-1] = null;
}
} }

2.

 package headfirst.designpatterns.iterator.dinermergercafe;

 import java.util.Iterator;

 public class DinerMenu implements Menu {
static final int MAX_ITEMS = 6;
int numberOfItems = 0;
MenuItem[] menuItems; public DinerMenu() {
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 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);
addItem("Steamed Veggies and Brown Rice",
"A medly of steamed vegetables over brown rice", true, 3.99);
addItem("Pasta",
"Spaghetti with Marinara Sauce, and a slice of sourdough bread",
true, 3.89);
} 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 = numberOfItems + 1;
}
} public MenuItem[] getMenuItems() {
return menuItems;
} public Iterator<MenuItem> createIterator() {
return new DinerMenuIterator(menuItems);
//return new AlternatingDinerMenuIterator(menuItems);
} // other menu methods here
}

3.用hashmap

 package headfirst.designpatterns.iterator.dinermergercafe;

 import java.util.*;

 public class CafeMenu implements Menu {
HashMap<String, MenuItem> menuItems = new HashMap<String, MenuItem>(); public CafeMenu() {
addItem("Veggie Burger and Air Fries",
"Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
true, 3.99);
addItem("Soup of the day",
"A cup of the soup of the day, with a side salad",
false, 3.69);
addItem("Burrito",
"A large burrito, with whole pinto beans, salsa, guacamole",
true, 4.29);
} public void addItem(String name, String description,
boolean vegetarian, double price)
{
MenuItem menuItem = new MenuItem(name, description, vegetarian, price);
menuItems.put(menuItem.getName(), menuItem);
} public Map<String, MenuItem> getItems() {
return menuItems;
} public Iterator<MenuItem> createIterator() {
return menuItems.values().iterator();
}
}

HeadFirst设计模式之迭代器模式的更多相关文章

  1. 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)

    原文:乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) 作者:weba ...

  2. Python进阶:设计模式之迭代器模式

    在软件开发领域中,人们经常会用到这一个概念——“设计模式”(design pattern),它是一种针对软件设计的共性问题而提出的解决方案.在一本圣经级的书籍<设计模式:可复用面向对象软件的基础 ...

  3. 设计模式学习--迭代器模式(Iterator Pattern)和组合模式(Composite Pattern)

    设计模式学习--迭代器模式(Iterator Pattern) 概述 ——————————————————————————————————————————————————— 迭代器模式提供一种方法顺序 ...

  4. js设计模式——4.迭代器模式

    js设计模式——4.迭代器模式 代码演示 /*js设计模式——迭代器模式*/ class Iterator { constructor(container) { this.list = contain ...

  5. 实践GoF的设计模式:迭代器模式

    摘要:迭代器模式主要用在访问对象集合的场景,能够向客户端隐藏集合的实现细节. 本文分享自华为云社区<[Go实现]实践GoF的23种设计模式:迭代器模式>,作者:元闰子. 简介 有时会遇到这 ...

  6. 【GOF23设计模式】迭代器模式

    来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_迭代器模式.JDK内置迭代器.内部类迭代器 package com.test.iterator; /** * 自定义的迭代 ...

  7. [设计模式] 16 迭代器模式 Iterator Pattern

    在GOF的<设计模式:可复用面向对象软件的基础>一书中对迭代器模式是这样说的:提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示. 类图和实例: 迭代器模式由以下角 ...

  8. php设计模式之迭代器模式

    今天的PHP设计模式系列的主角是迭代器(Iterator)模式,迭代器模式提供了抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代. 迭代器(Iterator)模式,它在一个很常见的过程上提供了 ...

  9. 设计模式之迭代器模式(Iterator)摘录

    23种GOF设计模式一般分为三大类:创建型模式.结构型模式.行为模式. 创建型模式抽象了实例化过程,它们帮助一个系统独立于怎样创建.组合和表示它的那些对象.一个类创建型模式使用继承改变被实例化的类,而 ...

随机推荐

  1. (转)优化tomcat,提高网站运行速度

    网站优化方案: 网站优化有很多方面,这里我们先主要讲讲 tomcat优化.[主要针对tomcat6.0及以上版本] 1.  为jvm增加更多的内存,tomcat安装时,默认为126M,可以设置. To ...

  2. info sed 中文不完全文档

    快速指南: sed 的一般使用方法:sed -option 'adress|command' -f scpritfiles(1)'|' 只是用来说明性的分隔 adress 和 command,实际使用 ...

  3. cplusplus解析

    经常在头文件包含代码里面看到如下代码 #ifndef MAC_API_H #define MAC_API_H #ifdef __cplusplus extern "C"{ #end ...

  4. 实现cookie跨域访问

    需求:A系统(www.a.com)里设置一个浏览器cookie,B系统(www.b.com)需要能够访问到A设置的cookie. 通过HTML SCRIPT标签跨域写cookie: 由于html的sc ...

  5. JSONP VS CORS

    What is JSONP ? http://stackoverflow.com/questions/2067472/what-is-jsonp-all-about What is CORS? htt ...

  6. WinForm C#全局错误捕捉处理【整理】

    static class Program { /// <summary> /// 应用程序的主入口点. /// </summary> [STAThread] static vo ...

  7. (转载)sql语句解决分页问题

    <来源网址:http://www.delphifans.com/infoview/Article_353.html>sql语句解决分页问题日期:2005年1月17日 作者:treemon2 ...

  8. win10 安装scrapy

    在win10的环境下安装scrapy,并不能直接按照官网的手册(http://doc.scrapy.org/en/1.0/intro/install.html)一次性安装成功,根据我自己的安装过程中遇 ...

  9. 【Java Web】Eclipse中配置Marven环境

    1  Marven简介 Apache Maven,是一个软件(特别是Java软件)项目管理及自动构建工具,由Apache软件基金会所提供.基于项目对象模型(缩写:POM)概念,Maven利用一个中央信 ...

  10. zhuan:ubuntu下安装Apache2+php+Mysql

    from: http://www.cnblogs.com/lynch_world/archive/2012/01/06/2314717.html ubuntu下安装Apache+PHP+Mysql 转 ...