迭代模式(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

版权声明:本文博客原创文章,博客,未经同意,不得转载。

设计模式 - 迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释的更多相关文章

  1. 设计模式 - 命令模式(command pattern) 宏命令(macro command) 具体解释

    命令模式(command pattern) 宏命令(macro command) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考: 命名模式(撤销) ...

  2. 24种设计模式--迭代模式【Iterator Pattern】

    周五下午,我正在看技术网站,第六感官发觉有人在身后,扭头一看,我 C,老大站在背后,赶忙站起来,“王经理,你找我?” 我说. “哦,在看技术呀.有个事情找你谈一下,你到我办公室来一下.” 老大说. 到 ...

  3. 设计模式 - 组合模式(composite pattern) 迭代器(iterator) 具体解释

    组合模式(composite pattern) 迭代器(iterator) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考组合模式(composit ...

  4. [转载]Java迭代器(iterator详解以及和for循环的区别)

    Java迭代器(iterator详解以及和for循环的区别) 觉得有用的话,欢迎一起讨论相互学习~[Follow] 转载自 https://blog.csdn.net/Jae_Wang/article ...

  5. 设计模式 - 装饰者模式(Decorator Pattern) Java的IO类 用法

    装饰者模式(Decorator Pattern) Java的IO类 用法 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26716 ...

  6. Java 迭代器 Iterator

    迭代器模式 迭代器模式(Iterator Pattern)是 Java 和 .Net 编程环境中非常常用的设计模式.这种模式用于顺序访问集合对象的元素,不需要知道集合对象的底层表示. 迭代器模式属于行 ...

  7. Java迭代器Iterator

    之前我们实现了迭代器模式,很多编程语言实际上已经内置了迭代器类,比如Java就为我们实现了迭代器Iterator.我们首先来看Iterator中的源码. 通过JDK源码我们发现Iterator是一个接 ...

  8. java 迭代器iterator

    对于如ArrayList<E>类的数据,常用iterator遍历. ArrayList<String> list = new ArrayList<String>() ...

  9. 备忘录模式-Memento Pattern(Java实现)

    备忘录模式-Memento Pattern Memento备忘录设计模式是一个保存另外一个对象内部状态拷贝的对象,这样以后就可以将该对象恢复到以前保存的状态. 本文中的场景: 有一款游戏可以随时存档, ...

随机推荐

  1. SQLServer2014新功能

    随机存取存储器 OLTP:提供了内置在芯 SQL Server 数据库内存 OLTP 特征,为了显著提高事务数据库应用程序的速度和吞吐量.随机存取存储器 OLTP 它是包含在 SQL Server 2 ...

  2. Dom4j分解xml

    package cn.com.guju.util; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingExc ...

  3. 【Linux探索之旅】第一部分测试题

    内容简介 1.第一部分测试题 2.第二部分第一课预告:终端Terminal,好戏上场 10道测试题 让我们选择开机时进哪个操作系统的软件叫什么? A. booter B. bootloader C. ...

  4. 深入浅出JMS(一)——JMS简要

    假设手机只能实时通话.没有邮件和短信功能发生?一个电话回来.只是没有足够的时间去连接.然后传递这款手机的信息肯定是不接受. 么不能先将信息存下来.当用户须要查看信息的时候再去获得信息呢?伴随着这个疑惑 ...

  5. Hibernate HQL详细说明

    1.  Hibernate HQL详细说明 1.1.  hql一个简短的引论 Hibernate它配备了一种非常强大的查询语言.这种语言看起来非常像SQL.但是不要 要对相位的语法结构似,HQL是很有 ...

  6. Discuz 楼主帖子采集

    try { ; i < ; i++) { var html = GetHtmls("http://bbs.fobshanghai.com/viewthread.php?tid=3885 ...

  7. XML数据读取方式性能比较(一)

    原文:XML数据读取方式性能比较(一) 几个月来,疑被SOA,一直在和XML操作打交道,SQL差不多又忘光了.现在已经知道,至少有四种常用人XML数据操作方式(好像Java差不多),不过还没有实际比较 ...

  8. ti8168 eth0 启动

    ti8168 原始文件系统进去后没有网络eth0接口,为了有该接口须要配置/etc/network/interfaces 文件 详细配置例如以下(红色要配置) # /etc/network/inter ...

  9. IE8/IE9无法启用JavaScript怎么办

    在IE8/IE9 中,有些同学在浏览网页时,收到提示:“需要启用 JavaScript …”,并且会发现网页上某些功能不能用了,比如点击网页里的按钮没反应等等.这个是因为浏览器的JavaScript ...

  10. C++四种类型的转换

    在C/C++使用的语言 (type) value(您还可以使用type(value))对于显式类型转换,经常提到投.转换程序猿的精度等完全掌握手,一个传统投往往是过度使用.成为C++要根源. 为了降低 ...