设计模式 - 组合模式(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 ...
随机推荐
- SpringBoot学习笔记(10)-----SpringBoot中使用Redis/Mongodb和缓存Ehcache缓存和redis缓存
1. 使用Redis 在使用redis之前,首先要保证安装或有redis的服务器,接下就是引入redis依赖. pom.xml文件如下 <dependency> <groupId&g ...
- 复制excel表,往excel表中写入数据
import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import jav ...
- map循环遍历
data.map(function(item){ item.show = false; //将拿到的data循环给每一项添加show属性 });
- React项目构建(利用webpack打包)
引言 最近React作为当前最为火热的前端框架.最近也相继而出来相关ES7的新语法. 当然,在使用React开发web项目的时候,不得不提到的就是与之配套的相应的打包技术,之前上文已经简单的提到Rea ...
- Python数据分析前提-----pandas
1.read_csv(url):读取数据 2.help(read_csv):打印函数相关用法 3.数据名.dtypes:读取数据的类型(int.float……) 4.type(数据名):读取所有数据的 ...
- HDU-3746 Cyclic Nacklace 字符串匹配 KMP算法 求最小循环节
题目链接:https://cn.vjudge.net/problem/HDU-3746 题意 给一串珠子,我们可以在珠子的最右端或最左端加一些珠子 问做一条包含循环珠子的项链,最少还需要多少珠子 思路 ...
- UVA-1602 Lattice Animals 搜索问题(打表+set)
题目链接 https://vjudge.net/problem/UVA-1602 紫书的一道例题,跟之前的很多题目有很多不同. 本题不像是一般的dfs或bfs这样的搜索套路,而是另一种枚举思路. 题意 ...
- [codevs3269]混合背包
题目大意:一道混合背包模板. 解题思路:分三种情况讨论,01和完全没什么问题,多重背包需要把物品分成$\log W[i]$件,然后01即可,分成W[i]件01会TLE. 读优大法好! C++ Code ...
- javaweb实现教师和教室管理系统 java jsp sqlserver
1,程序设计思想 (1)设计三个类,分别是工具类(用来写连接数据库的方法和异常类的方法).信息类(用来写存储信息的方法).实现类(用来写各种操作数据库的方法) (2)定义两个jsp文件,一个用来写入数 ...
- 【codeforces 65A】Harry Potter and Three Spells
[题目链接]:http://codeforces.com/problemset/problem/65/A [题意] 你有3种魔法; 1.可以将a单位的石头变成b单位的铅 2.可以将c单位的铅变成d单位 ...