HeadFirst设计模式之迭代器模式
一、
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设计模式之迭代器模式的更多相关文章
- 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern)
原文:乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 迭代器模式(Iterator Pattern) 作者:weba ...
- Python进阶:设计模式之迭代器模式
在软件开发领域中,人们经常会用到这一个概念——“设计模式”(design pattern),它是一种针对软件设计的共性问题而提出的解决方案.在一本圣经级的书籍<设计模式:可复用面向对象软件的基础 ...
- 设计模式学习--迭代器模式(Iterator Pattern)和组合模式(Composite Pattern)
设计模式学习--迭代器模式(Iterator Pattern) 概述 ——————————————————————————————————————————————————— 迭代器模式提供一种方法顺序 ...
- js设计模式——4.迭代器模式
js设计模式——4.迭代器模式 代码演示 /*js设计模式——迭代器模式*/ class Iterator { constructor(container) { this.list = contain ...
- 实践GoF的设计模式:迭代器模式
摘要:迭代器模式主要用在访问对象集合的场景,能够向客户端隐藏集合的实现细节. 本文分享自华为云社区<[Go实现]实践GoF的23种设计模式:迭代器模式>,作者:元闰子. 简介 有时会遇到这 ...
- 【GOF23设计模式】迭代器模式
来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_迭代器模式.JDK内置迭代器.内部类迭代器 package com.test.iterator; /** * 自定义的迭代 ...
- [设计模式] 16 迭代器模式 Iterator Pattern
在GOF的<设计模式:可复用面向对象软件的基础>一书中对迭代器模式是这样说的:提供一种方法顺序访问一个聚合对象中各个元素,而又不需要暴露该对象的内部表示. 类图和实例: 迭代器模式由以下角 ...
- php设计模式之迭代器模式
今天的PHP设计模式系列的主角是迭代器(Iterator)模式,迭代器模式提供了抽象:位于对象图不明部分的一组对象(或标量)集合上的迭代. 迭代器(Iterator)模式,它在一个很常见的过程上提供了 ...
- 设计模式之迭代器模式(Iterator)摘录
23种GOF设计模式一般分为三大类:创建型模式.结构型模式.行为模式. 创建型模式抽象了实例化过程,它们帮助一个系统独立于怎样创建.组合和表示它的那些对象.一个类创建型模式使用继承改变被实例化的类,而 ...
随机推荐
- IPointCollection转IPolyline
IPointCollection转线IPolyline: IPolyline pl = new PolylineClass(); IPointCollection ptc = pl as IPoint ...
- Linux 锁
问题: 1.假如对某个文件加了锁/lock,但是程序退出时没有关闭锁,如果想在另外一个程序中用这个文件,如何办? 2.
- 学习C++ Primer 的个人理解(一)
<C++ Primer>这本书可以说是公认的学习C++最好的书,但我觉得不是特别适合作为教材,书中内容的顺序让人有些蛋疼.我个人认为初学此书是不能跳着看的.如果急于上手的话,我更推荐< ...
- office2013发布博客
0, 喜欢用world记笔记,并查上一些配图.但是再想重新发到博客上,图片不得不重新上传十分蛋疼. world直接发布博客功能太棒了,直接绑定账号和url就可以发送了,爽YY!!! 1,新建一个博客文 ...
- 【转帖】error C2296: “^”: 非法,左操作数包含“double”类型
想要实现 ,写的C++程序为 double x; x=2^3; 结果程序总是出现这样的错误:error C2296: “^”: 非法,左操作数包含“double”类型 后来才发现操作符“^”,在C++ ...
- HTML5之 Microdata微数据
- 为何需要微数据 长篇加累版牍,不好理解 微标记来标注其中内容,让其容易识辨 - RDFa Resource Description Framework http://www.w3.org/TR/m ...
- Projected Coordinate Systems
Coordinate Systems Projected Coordinate Systems This is an archive of a previous version of the ArcG ...
- C#委托的异步调用
本文将主要通过“同步调用”.“异步调用”.“异步回调”三个示例来讲解在用委托执行同一个“加法类”的时候的的区别和利弊. 首先,通过代码定义一个委托和下面三个示例将要调用的方法: /*添加的命名空间 u ...
- 【原】Oracle查询指定表里的触发器
select * from all_triggers WHERE table_name='表名'
- Openvpn完美解决公司网络没有固定公网IP的问题
方案背景: 公司办公网络使用长城宽带上网有一段时间了,有4个固定IP(2个电信,2个网通),链路不太稳定,经常有问题,因此考虑取消长城宽带,采用原来的adsl上网.但是有个问题,因为公司内网有几台服务 ...