设计模式 - 组合模式(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 ...
随机推荐
- Paper Reading: Relation Networks for Object Detection
Relation Networks for Object Detection笔记 写在前面:关于这篇论文的背景知识,请参考我前面的两篇随笔(<关于目标检测>和<关于注意力机制> ...
- NOIp2018模拟赛三十六
好久没打模拟赛了...今天一样是两道国集,一道bzoj题 成绩:13+0+95=108 A题开始看错题了...导致样例都没看懂,结果xfz提醒我后我理解了一个我自认为正确的题意(事实证明我和xfz都错 ...
- 学习CV:《OpenCV 3计算机视觉Python语言实现第2版》中文PDF+英文PDF+代码
理解与计算机视觉相关的算法.模型以及OpenCV 3 API背后的基本概念,有助于开发现实世界中的各种应用程序(比如:安全和监视领域的工具). OpenCV 3是一种先进的计算机视觉库,可以用于各种图 ...
- ubuntu安装和使用
1.查看ubuntu是32位还是64位 教程:jingyan.baidu.com/article/db55b609ab531f4ba30a2f13.html 2.安装maven 教程:www.linu ...
- 你可能需要了解下Laravel集合
前言 集合通过 Illuminate\Support\Collection 进行实例,Laravel的内核大部分的参数传递都用到了集合,但这并不代表集合就是好的.Laravel作为快捷并优雅的开发框架 ...
- 养活一款APP要“烧”多少钱?
Duang!又一款APP刷爆朋友圈.大片范儿的电影截图.意味深长的经典对白均出自一款名为“足记”的APP. 足记团队刚于去年8月完成天使期融资,投资方是光速创投和紫辉创投,目前正准备A轮融资.且近一周 ...
- 关于ValueAnimation以及Interpolator +Drawable实现的自己定义动画效果
ValueAnimation : Android中的属性动画,他跟objectAnimation是比补间动画拥有更强大的功能,能够操作对象.所以我们能够在自 定义View中通过他们来实现些特别的功能. ...
- TODOList 多线程交互、RCP、事物控制、数据倾斜、HBase数据同步性
TODOList 多线程交互.RCP.事物控制.数据倾斜.HBase数据同步性 TODO List thread.join()如何互相之间通知? 线程池何时最后运行完成? MemCache性能要优于R ...
- TCP/IP、UDP、 Http、Socket的差别
网络由上往下分为: 表示层和应用层 :HTTP协议(基于传输层的TCP协议,主要解决怎样包装数据) 会话层 传输层: TCP协议(基于网络层的IP协议).TPC/IP协议(主要解决数据怎样在网络中传输 ...
- HDU 2112 HDU Today <SPFA算法+map函数>
HDU Today Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total ...