设计模式 - 组合模式(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) 详解,布布扣,bubuko.com

时间: 2024-07-30 10:17:56

设计模式 - 组合模式(composite pattern) 迭代器(iterator) 详解的相关文章

设计模式 - 组合模式(composite pattern) 详解

组合模式(composite pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy 组合模式: 允许你将对象组合成树形结构来表现"整体/部分"层次结构. 组合能让客户以一致的方法处理个别对象以及组合对象. 建立组件类(Component), 组合类(composite)和叶子类(leaf)继承组件类, 客户类(client)直接调用最顶层的组合类(composite)即可. 具体方法: 1. 组件类(component), 包含组合

设计模式 - 命令模式(command pattern) 多命令 详解

命令模式(command pattern) 多命令 详解 本文地址: http://blog.csdn.net/caroline_wendy 参考命令模式: http://blog.csdn.net/caroline_wendy/article/details/31379977 具体步骤: 1. 多命令, 把未使用的命令, 初始化为空对象(NoCommand), 根据参数(slot), 选择输出命令. /** * @time 2014年6月16日 */ package command; /**

设计模式 - 命令模式(command pattern) 撤销(undo) 详解

命令模式(command pattern) 撤销(undo) 详解 本文地址: http://blog.csdn.net/caroline_wendy 参考命令模式: http://blog.csdn.net/caroline_wendy/article/details/31379977 命令模式可以用于执行撤销(undo)操作. 具体方法: 1. 对象类中需要保存状态, 如level. package command; public class CeilingFan { String loca

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

定义: 对象组合成部分整体结构,单个对象和组合对象具有一致性. 看了下大概结构就是集团总公司和子公司那种层级结构. 角色介绍: Component :抽象根节点:其实相当去总公司,抽象子类共有的方法: Composite :相当于总公司的智能部门,也分管子公司,通过集合存储子节点对象,提供增删获取子节点对象的方法: leaf:子节点,相当于集团子公司,总公司具有的智能,子公司也具有,因此子节点具有总节点拥有的所有抽象方法以及提供给子类的方法. Client:通过抽象跟节点操作子节点的对象.

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

迭代器模式(iterator pattern) Java 迭代器(Iterator) 详解 本文地址: http://blog.csdn.net/caroline_wendy 参考迭代器模式(iterator pattern): http://blog.csdn.net/caroline_wendy/article/details/35254643 Java的标准库(util)中包含迭代器接口(iterator interface), import java.util.Iterator; 继承(

设计模式之组合模式---Composite Pattern

模式的定义 组合模式(Composite Pattern)定义如下: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. 将对象组合成树形结构以表示"部分-整体"的层次结构,使得用户对单个对象和组合对象的使用具有一致性.

说说设计模式~组合模式(Composite)

返回目录 何时能用到它? 组合模式又叫部分-整体模式,在树型结构中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦.对于今天这个例子来说,它可以很清楚的说明组合模式的用意,首先是一个Graphics对象,它表示是一绘图功能(树根),而circle,line和rectangle分别是简单的图形,它们内部不能再有其它图形了(相当于树叶),而picture是一个复杂图形,它由circle,line和rectangle组成(相当于树

组合模式(Composite Pattern)

转:http://www.cnblogs.com/doubleliang/archive/2011/12/27/2304104.html 简而言之,就是让所有的叶子节点执行相同的操作!!!!!!!!!!!!!!! 组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性. 有时候又叫做部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构

设计模式(结构型)之组合模式(Composite Pattern)

PS一句:最终还是选择CSDN来整理发表这几年的知识点,该文章平行迁移到CSDN.因为CSDN也支持MarkDown语法了,牛逼啊! [工匠若水 http://blog.csdn.net/yanbober] 阅读前一篇<设计模式(结构型)之桥接模式(Bridge Pattern)> http://blog.csdn.net/yanbober/article/details/45366781 概述 组合模式又叫做部分-整体模式,使我们在树型结构的问题中模糊简单元素和复杂元素的概念,客户程序可以像