组合模式(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) 具体解释的更多相关文章

  1. 浅谈设计模式--组合模式(Composite Pattern)

    组合模式(Composite Pattern) 组合模式,有时候又叫部分-整体结构(part-whole hierarchy),使得用户对单个对象和对一组对象的使用具有一致性.简单来说,就是可以像使用 ...

  2. 设计模式 -- 组合模式 (Composite Pattern)

    定义: 对象组合成部分整体结构,单个对象和组合对象具有一致性. 看了下大概结构就是集团总公司和子公司那种层级结构. 角色介绍: Component :抽象根节点:其实相当去总公司,抽象子类共有的方法: ...

  3. C#设计模式——组合模式(Composite Pattern)

    一.概述 在软件开发中,我们往往会遇上类似树形结构的对象体系.即某一对象既可能在树形结构中作为叶节点存在,也可能作为分支节点存在.比如在文件系统中,文件是作为叶节点存在,而文件夹就是分支节点.在设计这 ...

  4. 乐在其中设计模式(C#) - 组合模式(Composite Pattern)

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

  5. 设计模式系列之组合模式(Composite Pattern)——树形结构的处理

    说明:设计模式系列文章是读刘伟所著<设计模式的艺术之道(软件开发人员内功修炼之道)>一书的阅读笔记.个人感觉这本书讲的不错,有兴趣推荐读一读.详细内容也可以看看此书作者的博客https:/ ...

  6. 二十四种设计模式:组合模式(Composite Pattern)

    组合模式(Composite Pattern) 介绍将对象组合成树形结构以表示"部分-整体"的层次结构.它使得客户对单个对象和复合对象的使用具有一致性.示例有一个Message实体 ...

  7. 【设计模式】组合模式 Composite Pattern

    树形结构是软件行业很常见的一种结构,几乎随处可见,  比如: HTML 页面中的DOM,产品的分类,通常一些应用或网站的菜单,Windows Form 中的控件继承关系,Android中的View继承 ...

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

    命令模式(command pattern) 多命令 具体解释 本文地址: http://blog.csdn.net/caroline_wendy 參考命令模式: http://blog.csdn.ne ...

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

    命令模式(command pattern) 撤销(undo) 详细解释 本文地址: http://blog.csdn.net/caroline_wendy 參考命令模式: http://blog.cs ...

随机推荐

  1. ueditor 编辑器,自定义图片上传

    <div> <h1>完整demo</h1> <form method="post" name="form"> & ...

  2. springboot ajax返回html

    因为拦截器 或者是 shiro  拦截登陆接口

  3. mven系列问题

    1.前言 Maven,发音是[`meivin],"专家"的意思.它是一个很好的项目管理工具,很早就进入了我的必备工具行列,但是这次为了把 project1项目完全迁移并应用mave ...

  4. redhat 7 cenos 7 网络配置文件

    Cenos 7 TYPE=Ethernet PROXY_METHOD=none BROWSER_ONLY=no DEFROUTE=yes IPV4_FAILURE_FATAL=no NAME=eth0 ...

  5. 常见WEB错误代码

    404表示文件或资源未找到 java WEB常见的错误代码 1.1xx-信息提示:这些状态代码表示临时的响应.客户端在收到常规响应之前,应准备接收一个或多个1xx响应. 100-继续. 101-切换协 ...

  6. UVALive 3989 Ladies' Choice

    Ladies' Choice Time Limit: 6000ms Memory Limit: 131072KB This problem will be judged on UVALive. Ori ...

  7. hadoop 2.6.0 LightWeightGSet源码分析

    LightWeightGSet的作用用一个数组来存储元素,而且用链表来解决冲突.不能rehash.所以内部数组永远不用改变大小.此类不支持空元素. 此类也不是线程安全的.有两个类型參数.第一个用于查找 ...

  8. unity3D常见问题

    总结自己在学习中遇到的问题. 记录问题,帮助他人,有什么不正确的地方欢迎指正 没有发生碰撞 两个物体(Plane和Cube)都加入了collider,当中一个加入了rigidbody,应该会产生碰撞, ...

  9. JavaSript之prototype属性

    近期在JavaSript进行Array操作的时候发现没有删除节点的方法.而我要实现的效果须要不断调用删除节点的方法.查找了相关资料发现能够利用prototype属性给Array添加删除节点的方法.而且 ...

  10. sage开发url替换字符串

    /// <summary>         /// Url字段值替换,无该字段则加入         /// </summary>         /// <param ...