迭代器模式(iterator pattern) 详细解释

本文地址: http://blog.csdn.net/caroline_wendy

迭代器模式(iterator pattern) : 提供一种方法顺序訪问一个聚合对象中的各个元素, 而又不暴露其内部的表示;

建立迭代器接口(iterator interface), 包括hasNext()方法和next()方法;

不同聚合对象的详细的迭代器(concrete iterator), 继承(implements)迭代器接口(iterator interface), 实现hasNext()方法和next()方法;

详细聚合对象(concrete aggregate), 提供创建迭代器的方法(createIterator).

通过调用聚合对象的迭代器, 就可以使用迭代器, 统一输出接口.

面向对象设计原则:

一个类应该仅仅有一个引起变化的原因.

即一个类应该仅仅有一个责任, 即高内聚.

详细方法:

1. 菜单项, 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;
} }

2. 详细的聚合对象(concrete aggregate), 包括创建迭代器的方法(createIterator).

/**
* @time 2014年6月26日
*/
package iterator; /**
* @author C.L.Wang
*
*/
public class DinerMenu { 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 createIterator() {
return new DinerMenuIterator(menuItems);
} } /**
* @time 2014年6月20日
*/
package iterator; import java.util.ArrayList; /**
* @author C.L.Wang
*
*/
public class PancakeHouseMenu { 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 createIterator() {
return new PancakeHouseMenuIterator(menuItems);
} }

3. 迭代器接口(iterator interface), 包括hasNext()方法next()方法.

/**
* @time 2014年6月27日
*/
package iterator; /**
* @author C.L.Wang
*
*/
public interface Iterator { boolean hasNext();
Object next(); }

4. 聚合对象的详细的迭代器(concrete iterator)继承(implements)迭代器接口(iterator interface), 实现hasNext()方法和next()方法;

/**
* @time 2014年6月27日
*/
package iterator; /**
* @author C.L.Wang
*
*/
public class DinerMenuIterator implements Iterator { 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 Object next() {
// TODO Auto-generated method stub MenuItem menuItem = items[position];
++position; return menuItem;
} } /**
* @time 2014年6月27日
*/
package iterator; import java.util.ArrayList; /**
* @author C.L.Wang
*
*/
public class PancakeHouseMenuIterator implements Iterator { ArrayList<MenuItem> menuItems;
int position; /**
*
*/
public PancakeHouseMenuIterator(ArrayList<MenuItem> menuItems) {
// TODO Auto-generated constructor stub
this.menuItems = menuItems;
} /* (non-Javadoc)
* @see iterator.Iterator#hasNext()
*/
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
if (position >= menuItems.size() || menuItems.get(position) == null) {
return false;
} return true;
} /* (non-Javadoc)
* @see iterator.Iterator#next()
*/
@Override
public Object next() {
// TODO Auto-generated method stub MenuItem menuItem = menuItems.get(position);
++position; return menuItem;
} }

5. 客户类使用详细聚合类(concrete aggregate)迭代器(iterator).

/**
* @time 2014年6月27日
*/
package iterator; /**
* @author C.L.Wang
*
*/
public class Waitress { PancakeHouseMenu pancakeHouseMenu;
DinerMenu dinerMenu; /**
*
*/
public Waitress(PancakeHouseMenu pancakeHouseMenu, DinerMenu dinerMenu) {
// TODO Auto-generated constructor stub
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 = (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) 具体解释的更多相关文章

  1. C#设计模式——迭代器模式(Iterator Pattern)

    一.概述在软件开发过程中,我们可能会希望在不暴露一个集合对象内部结构的同时,可以让外部代码透明地访问其中包含的元素.迭代器模式可以解决这一问题.二.迭代器模式迭代器模式提供一种方法顺序访问一个集合对象 ...

  2. 设计模式 - 迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释

    迭代模式(iterator pattern) Java 迭代器(Iterator) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy 參考迭代器模式(ite ...

  3. 设计模式(十):从电影院中认识"迭代器模式"(Iterator Pattern)

    上篇博客我们从醋溜土豆丝与清炒苦瓜中认识了“模板方法模式”,那么在今天这篇博客中我们要从电影院中来认识"迭代器模式"(Iterator Pattern).“迭代器模式”顾名思义就是 ...

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

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

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

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

  6. 设计模式系列之迭代器模式(Iterator Pattern)——遍历聚合对象中的元素

    模式概述 模式定义 模式结构图 模式伪代码 模式改进 模式应用 模式在JDK中的应用 模式在开源项目中的应用 模式总结 说明:设计模式系列文章是读刘伟所著<设计模式的艺术之道(软件开发人员内功修 ...

  7. 二十四种设计模式:迭代器模式(Iterator Pattern)

    迭代器模式(Iterator Pattern) 介绍提供一种方法顺序访问一个聚合对象中各个元素,而又不需暴露该对象的内部表示. 示例有一个Message实体类,某聚合对象内的各个元素均为该实体对象,现 ...

  8. 设计模式 - 策略模式(Strategy Pattern) 具体解释

    策略模式(Strategy Pattern) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26577879 本文版权全 ...

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

    命令模式(command pattern) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy 命令模式(command pattern) : 将请求封装成对 ...

随机推荐

  1. 141. Linked List Cycle【Easy】【判断链表是否存在环】

    Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked lis ...

  2. 排序小记【2】对 struct 的排序

    有了前面的内容,对于一般的排序已经没有问题了,但是有时候排序的要求可能会有点刁... 举个简单的例子,应该是NOIP2009的分数线划定,差不多算是一个比较高级的排序(吧). 多关键字排序(?) 我一 ...

  3. 【思路】Gym - 101173F - Free Figurines

    套娃形成一些链形结构,给你套娃的初始状态和目标状态,问你需要几步(将最外层套娃打开,以及将一整套套娃塞进一个空套娃都算一步)才能达到. 容易发现,只有每条链链尾的匹配段可以不拆,其他的都得拆开. #i ...

  4. 记录SSD中的一些东西

    AnnotatedDatum是存放图片和BBox的类 // 估计是一张图片就对应于一个AnnotatedDatummessage AnnotatedDatum { enum AnnotationTyp ...

  5. #iOS问题记录# UITextview富文本链接,禁止长按事件

    UITextView的富文本组装,添加图片点击事件,启动 - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *) ...

  6. [Bug]IE11下,forms认证,出现无法保存cookie的问题

    目录 ie11 解决方案 ie11 在ie11下,访问服务器上的网站地址,莫名其妙的多出一串东西,这一串字符串是由于客户端禁用cookie造成sessionid无法写入cookie,所以就拼在url上 ...

  7. 统计中的f检验和t检验的区别

    参考:http://emuch.net/html/201102/2841741.html 首先是目的不同.F检验用于比较两种分析方法是否存在显著差异(单边检验)或者两种方法紧密度是否存在差异(双边检验 ...

  8. iOS:多线程的详细介绍

    多线程: 一.概念 1.什么是进程?     程序的一次性执行就是进程.进程占独立的内存空间.   2.什么是线程?     进程中的代码的执行路径.   3.进程与线程之间的关系?      每个进 ...

  9. cc攻击技术

    攻击者借助代理服务器生成指向受害主机的合法请求,实现DOS,和伪装就叫:cc(ChallengeCollapsar). CC主要是用来攻击页面的.大家都有这样的经历,就是在访问论坛时,如果这个论坛比较 ...

  10. stylus使用文档总结:选择器+变量+插值+运算符+混合书写+方法

    建立好项目后我们来安装stylus npm install stylus stylus-loader --save-dev 这样就安装上了stylus. 接下来就可以使用了,使用方式分两种.一种是在. ...