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设计模式一般分为三大类:创建型模式.结构型模式.行为模式. 创建型模式抽象了实例化过程,它们帮助一个系统独立于怎样创建.组合和表示它的那些对象.一个类创建型模式使用继承改变被实例化的类,而 ...
随机推荐
- javascript笔记—— call 简单理解
call 方法 请参阅 应用于:Function 对象 要求 版本 5.5 调用一个对象的一个方法,以另一个对象替换当前对象. call([thisObj[,arg1[, arg2[, [,.argN ...
- day 0.
/* 嗯 就要结束了. OI生涯 2015.12-2016.11. 认识了很多人. 然后我这个学渣跟你们混在一起 感觉自卑至极啊. 好了 先不说这些伤心的话. Gryz小伙伴儿们NOIP RP++吧. ...
- 【转载】学习C++和编程的几个要点
1.把C++当成一门新的语言学习(和C没啥关系!真的.):2.看<ThinkingIn C++>,不要看<C++变成死相>:3.看<The C++ Programming ...
- 使用git的正确姿势
1.Windows上安装git:从https://git-for-windows.github.io下载msysgit. 2.linux(Debian或Ubuntu)安装git:sudo apt-ge ...
- 在Apache中开启虚拟主机
最近在自学LAMP,在Apache中尝试着开启虚拟主机的时候,遇到了挺多麻烦的,这里也顺便总结一下,在Apache中开启虚拟主机的时候,主要有下面几个步骤: 1.新建一个文件夹作为虚拟主机,用来存储网 ...
- Windows Phone 8.1 页面导航
1. Windows Phone 8.1 的应用框架 一个应用拥有 1 个 Window,一个 Window 包含 1 个 Frame,一个 Frame 包含 多个 Page. 获取 Frame 的方 ...
- 巧用Systemtap注入延迟模拟IO设备抖动
原创文章,转载请注明: 转载自系统技术非业余研究 本文链接地址: 巧用Systemtap注入延迟模拟IO设备抖动 当我们的IO密集型的应用怀疑设备的IO抖动,比如说一段时间的wait时间过长导致性能或 ...
- css圆角 四边投影
-moz-border-radius: 30px;-webkit-border-radius: 30px; border-radius:30px; -webkit-box-shadow:0 0 10p ...
- WeX5与阿里内测的Weex与有何纠葛?快来看HTML5开发圈那些逗逼事儿!
4月21日~23日,由infoQ主办的2016 Qcon大会北京站如期举行. HTML5开发已经成为移动开发/前端专题中无可争议的焦点,核心议题已经由前几年的是否该用HTML5转向了如何高性能.高效率 ...
- 模仿 ios 分段单选
http://blog.csdn.net/qduningning/article/details/37935227 res/drawable/seg_left.xml <?xml version ...