设计模式 - 组合模式(composite pattern) 迭代器(iterator) 具体解释
组合模式(composite pattern) 迭代器(iterator) 具体解释
本文地址: http://blog.csdn.net/caroline_wendy
參考组合模式(composite pattern): http://blog.csdn.net/caroline_wendy/article/details/36895627
在组合模式(composite pattern)加入迭代器功能, 遍历每个组合(composite)的项.
具体方法:
1. 抽象组件类(abstract component)加入创建迭代器的方法.
/**
* @time 2014年7月4日
*/
package composite; import java.util.Iterator; /**
* @author C.L.Wang
*
*/
public abstract class MenuComponent {
public void add(MenuComponent menuComponent) {
throw new UnsupportedOperationException(); //假设未提供, 则不能调用
}
public void remove(MenuComponent menuComponent) {
throw new UnsupportedOperationException();
}
public MenuComponent getChild(int i) {
throw new UnsupportedOperationException();
}
public String getName() {
throw new UnsupportedOperationException();
}
public String getDescription() {
throw new UnsupportedOperationException();
}
public double getPrice() {
throw new UnsupportedOperationException();
}
public boolean isVegetarian() {
throw new UnsupportedOperationException();
}
public void print() {
throw new UnsupportedOperationException();
}
public Iterator<MenuComponent> createIterator() {
throw new UnsupportedOperationException();
}
}
2. 组合迭代器类(composite iterator).
/**
* @time 2014年7月4日
*/
package composite; import java.util.Iterator;
import java.util.Stack; /**
* @author C.L.Wang
*
*/
public class CompositeIterator implements Iterator<MenuComponent> { Stack<Iterator<MenuComponent>> stack = new Stack<Iterator<MenuComponent>>(); /**
*
*/
public CompositeIterator(Iterator<MenuComponent> iterator) {
// TODO Auto-generated constructor stub
stack.push(iterator);
} public boolean hasNext() {
if (stack.empty()) {
return false;
} else {
Iterator<MenuComponent> iterator = (Iterator<MenuComponent>)stack.peek();
if (!iterator.hasNext()) {
stack.pop();
return hasNext(); //递归调用
} else {
return true;
}
}
} public MenuComponent next() {
if (hasNext()) {
Iterator<MenuComponent> iterator = (Iterator<MenuComponent>)stack.peek();
MenuComponent component = (MenuComponent)iterator.next();
if (component instanceof Menu) {
stack.push(component.createIterator());
}
return component;
} else {
return null;
}
} public void remove() {
throw new UnsupportedOperationException();
} }
3. 组合类(composite)实现创建迭代器的方法, 并创建组合迭代器(composite iterator).
/**
* @time 2014年7月4日
*/
package composite; import java.util.ArrayList;
import java.util.Iterator; /**
* @author C.L.Wang
*
*/
public class Menu extends MenuComponent { ArrayList<MenuComponent> menuComponents = new ArrayList<MenuComponent>();
String name;
String description; /**
*
*/
public Menu(String name, String description) {
// TODO Auto-generated constructor stub
this.name = name;
this.description = description;
} public void add(MenuComponent menuComponent) {
menuComponents.add(menuComponent);
} public void remove(MenuComponent menuComponent) {
menuComponents.remove(menuComponent);
} public MenuComponent getChild(int i) {
return (MenuComponent)menuComponents.get(i);
}
public String getName() {
return name;
} public String getDescription() {
return description;
} public void print() {
System.out.print("\n" + getName());
System.out.println(", " + getDescription());
System.out.println("--------------------"); Iterator<MenuComponent> iterator = menuComponents.iterator();
while (iterator.hasNext()) {
MenuComponent menuComponent = (MenuComponent)iterator.next();
menuComponent.print();
}
} public Iterator<MenuComponent> createIterator() {
return new CompositeIterator(menuComponents.iterator());
} }
4. 叶子类(leaf)实现创建空迭代器(null iterator)的方法.
/**
* @time 2014年7月4日
*/
package composite; import java.util.Iterator; /**
* @author C.L.Wang
*
*/
public class NullIterator implements Iterator<MenuComponent> {
public MenuComponent next() {
return null;
}
public boolean hasNext() {
return false;
}
public void remove() {
throw new UnsupportedOperationException();
}
} /**
* @time 2014年7月4日
*/
package composite; import java.util.Iterator; /**
* @author C.L.Wang
*
*/
public class MenuItem extends MenuComponent { 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;
}
public void print() {
System.out.print(" " + getName());
if (isVegetarian()) {
System.out.print("(v)");
}
System.out.println(", " + getPrice());
System.out.println(" -- " + getDescription());
}
public Iterator<MenuComponent> createIterator() {
return new NullIterator();
}
}
5. 客户类.
/**
* @time 2014年7月4日
*/
package composite; import java.util.Iterator; /**
* @author C.L.Wang
*
*/
public class Waitress { MenuComponent allMenus;
/**
*
*/
public Waitress(MenuComponent allMenus) {
// TODO Auto-generated constructor stub
this.allMenus = allMenus;
} public void printMenu() {
allMenus.print();
} public void printVegetarianMenu() {
Iterator<MenuComponent> iterator = allMenus.createIterator();
System.out.println("\nVEGETARIAN MENU\n----");
while (iterator.hasNext()) {
MenuComponent menuComponent = (MenuComponent)iterator.next();
try {
if (menuComponent.isVegetarian())
menuComponent.print();
} catch (UnsupportedOperationException ex) {}
}
} }
6. 測试类
/**
* @time 2014年7月4日
*/
package composite; /**
* @author C.L.Wang
*
*/
public class MenuTestDrive { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MenuComponent pancakeHouseMenu = new Menu("PANCAKE HOUSE MENU", "Breakfast");
MenuComponent dinerMenu = new Menu("DINER MENU", "Lunch");
MenuComponent cafeMenu = new Menu("CAFE MENU", "Dinner");
MenuComponent dessertMenu = new Menu("DESSERT MENU", "Dessert course!");
MenuComponent coffeeMenu = new Menu("COFFEE MENU", "Stuff to go with your afternoon coffee"); MenuComponent allMenus = new Menu("ALL MENUS", "All menus combined"); allMenus.add(pancakeHouseMenu);
allMenus.add(dinerMenu);
allMenus.add(cafeMenu); pancakeHouseMenu.add(new MenuItem(
"K&B's Pancake Breakfast",
"Pancakes with scrambled eggs, and toast",
true,
2.99));
pancakeHouseMenu.add(new MenuItem(
"Regular Pancake Breakfast",
"Pancakes with fried eggs, sausage",
false,
2.99));
pancakeHouseMenu.add(new MenuItem(
"Blueberry Pancakes",
"Pancakes made with fresh blueberries, and blueberry syrup",
true,
3.49));
pancakeHouseMenu.add(new MenuItem(
"Waffles",
"Waffles, with your choice of blueberries or strawberries",
true,
3.59)); dinerMenu.add(new MenuItem(
"Vegetarian BLT",
"(Fakin') Bacon with lettuce & tomato on whole wheat",
true,
2.99));
dinerMenu.add(new MenuItem(
"BLT",
"Bacon with lettuce & tomato on whole wheat",
false,
2.99));
dinerMenu.add(new MenuItem(
"Soup of the day",
"A bowl of the soup of the day, with a side of potato salad",
false,
3.29));
dinerMenu.add(new MenuItem(
"Hotdog",
"A hot dog, with saurkraut, relish, onions, topped with cheese",
false,
3.05));
dinerMenu.add(new MenuItem(
"Steamed Veggies and Brown Rice",
"Steamed vegetables over brown rice",
true,
3.99)); dinerMenu.add(new MenuItem(
"Pasta",
"Spaghetti with Marinara Sauce, and a slice of sourdough bread",
true,
3.89)); dinerMenu.add(dessertMenu); dessertMenu.add(new MenuItem(
"Apple Pie",
"Apple pie with a flakey crust, topped with vanilla icecream",
true,
1.59)); dessertMenu.add(new MenuItem(
"Cheesecake",
"Creamy New York cheesecake, with a chocolate graham crust",
true,
1.99));
dessertMenu.add(new MenuItem(
"Sorbet",
"A scoop of raspberry and a scoop of lime",
true,
1.89)); cafeMenu.add(new MenuItem(
"Veggie Burger and Air Fries",
"Veggie burger on a whole wheat bun, lettuce, tomato, and fries",
true,
3.99));
cafeMenu.add(new MenuItem(
"Soup of the day",
"A cup of the soup of the day, with a side salad",
false,
3.69));
cafeMenu.add(new MenuItem(
"Burrito",
"A large burrito, with whole pinto beans, salsa, guacamole",
true,
4.29)); cafeMenu.add(coffeeMenu); coffeeMenu.add(new MenuItem(
"Coffee Cake",
"Crumbly cake topped with cinnamon and walnuts",
true,
1.59));
coffeeMenu.add(new MenuItem(
"Bagel",
"Flavors include sesame, poppyseed, cinnamon raisin, pumpkin",
false,
0.69));
coffeeMenu.add(new MenuItem(
"Biscotti",
"Three almond or hazelnut biscotti cookies",
true,
0.89)); Waitress waitress = new Waitress(allMenus); waitress.printVegetarianMenu();
} }
7. 输出.
VEGETARIAN MENU
----
K&B's Pancake Breakfast(v), 2.99
-- Pancakes with scrambled eggs, and toast
Blueberry Pancakes(v), 3.49
-- Pancakes made with fresh blueberries, and blueberry syrup
Waffles(v), 3.59
-- Waffles, with your choice of blueberries or strawberries
Vegetarian BLT(v), 2.99
-- (Fakin') Bacon with lettuce & tomato on whole wheat
Steamed Veggies and Brown Rice(v), 3.99
-- Steamed vegetables over brown rice
Pasta(v), 3.89
-- Spaghetti with Marinara Sauce, and a slice of sourdough bread
Apple Pie(v), 1.59
-- Apple pie with a flakey crust, topped with vanilla icecream
Cheesecake(v), 1.99
-- Creamy New York cheesecake, with a chocolate graham crust
Sorbet(v), 1.89
-- A scoop of raspberry and a scoop of lime
Apple Pie(v), 1.59
-- Apple pie with a flakey crust, topped with vanilla icecream
Cheesecake(v), 1.99
-- Creamy New York cheesecake, with a chocolate graham crust
Sorbet(v), 1.89
-- A scoop of raspberry and a scoop of lime
Veggie Burger and Air Fries(v), 3.99
-- Veggie burger on a whole wheat bun, lettuce, tomato, and fries
Burrito(v), 4.29
-- A large burrito, with whole pinto beans, salsa, guacamole
Coffee Cake(v), 1.59
-- Crumbly cake topped with cinnamon and walnuts
Biscotti(v), 0.89
-- Three almond or hazelnut biscotti cookies
Coffee Cake(v), 1.59
-- Crumbly cake topped with cinnamon and walnuts
Biscotti(v), 0.89
-- Three almond or hazelnut biscotti cookies
设计模式 - 组合模式(composite pattern) 迭代器(iterator) 具体解释的更多相关文章
- 浅谈设计模式--组合模式(Composite Pattern)
组合模式(Composite Pattern) 组合模式,有时候又叫部分-整体结构(part-whole hierarchy),使得用户对单个对象和对一组对象的使用具有一致性.简单来说,就是可以像使用 ...
- 设计模式 -- 组合模式 (Composite Pattern)
定义: 对象组合成部分整体结构,单个对象和组合对象具有一致性. 看了下大概结构就是集团总公司和子公司那种层级结构. 角色介绍: Component :抽象根节点:其实相当去总公司,抽象子类共有的方法: ...
- C#设计模式——组合模式(Composite Pattern)
一.概述 在软件开发中,我们往往会遇上类似树形结构的对象体系.即某一对象既可能在树形结构中作为叶节点存在,也可能作为分支节点存在.比如在文件系统中,文件是作为叶节点存在,而文件夹就是分支节点.在设计这 ...
- 乐在其中设计模式(C#) - 组合模式(Composite Pattern)
原文:乐在其中设计模式(C#) - 组合模式(Composite Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 组合模式(Composite Pattern) 作者:weba ...
- 设计模式系列之组合模式(Composite Pattern)——树形结构的处理
说明:设计模式系列文章是读刘伟所著<设计模式的艺术之道(软件开发人员内功修炼之道)>一书的阅读笔记.个人感觉这本书讲的不错,有兴趣推荐读一读.详细内容也可以看看此书作者的博客https:/ ...
- 二十四种设计模式:组合模式(Composite Pattern)
组合模式(Composite Pattern) 介绍将对象组合成树形结构以表示"部分-整体"的层次结构.它使得客户对单个对象和复合对象的使用具有一致性.示例有一个Message实体 ...
- 【设计模式】组合模式 Composite Pattern
树形结构是软件行业很常见的一种结构,几乎随处可见, 比如: HTML 页面中的DOM,产品的分类,通常一些应用或网站的菜单,Windows Form 中的控件继承关系,Android中的View继承 ...
- 设计模式 - 命令模式(command pattern) 多命令 具体解释
命令模式(command pattern) 多命令 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考命令模式: http://blog.csdn.ne ...
- 设计模式 - 命令模式(command pattern) 撤销(undo) 具体解释
命令模式(command pattern) 撤销(undo) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy 參考命令模式: http://blog.cs ...
随机推荐
- ActiveMQ学习笔记(5)----Broker的启动方式
Broker:相当于一个ActiveMQ服务器实例,在实际的开发中我们可以启动多个Broker. 命令行启动参数示例如下: 1. activemq start 使用默认的activemq.xml来启动 ...
- ActiveMQ学习笔记(2)----JMS的基本概念和模型
1. JMS 的基本概念 1. JMS是什么? JMS Java Message Service,Java消息服务,是Java EE中的一种技术. 2. JMS规范 JMS定义了Java中访问消息中间 ...
- VC++ 借助 Win32 API 绘图实现基本的细胞自动机演示
//本程序使用 Visual Studio 2015 生成的 Win32 窗口程序模板 开发//使用 Win32 API 绘图//实现基本的细胞自动机演示////目前已知问题://存在内存泄漏,但具体 ...
- scrapy框架学习
一.初窥Scrapy Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 可以应用在包括数据挖掘,信息处理或存储历史数据等一系列的程序中. 其最初是为了 页面抓取 (更确切来说, 网 ...
- vue父子组件通信传值
父组件 -> 子组件 通过props来进行通信 父组件代码: <Children :dataName = "dataContent" /> //dataName: ...
- 【问题】解决python3不支持mysqldb
Django框架使用的还是python2.x的MySQLdb,而python3.x使用的是pymysql,centos7上默认安装的python2.7,自己安装了python3.6的版本,在运行dja ...
- 操作指定文件格式的10个Perl CPAN模块
在Perl开发中,非常可能会碰到一些不同格式的文件--XML.PDF.CSV及RSS文件等,和一些不同的二进制数据格式.Perl应用程序须要操作这些文件,对它们进行读写. 此时.能够求助于全面Perl ...
- HDU 1542 Atlantis(矩形面积并)
HDU 1542 Atlantis 题目链接 题意:给定一些矩形,求面积并 思路:利用扫描线,因为这题矩形个数不多,直接暴力扫就能够了.假设数据大.就要用线段树 代码: #include <cs ...
- django 笔记17 ModelForm
Model 数据库操作 验证 验证 Form -class LoginForm(Form): email = fields.EmailField() is_valid 每一个字段进行正则(字段内置正则 ...
- 数据仓库 SSIS
SSDT 下载 :https://msdn.microsoft.com/en-us/library/mt204009.aspx Codeplex 上的 AdventureWorks 示例数据库此链接将 ...