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

组合模式(composite pattern) 详解

本文地址: http://blog.csdn.net/caroline_wendy

组合模式: 允许你将对象组合成树形结构来表现"整体/部分"层次结构. 组合能让客户以一致的方法处理个别对象以及组合对象.

建立组件类(Component), 组合类(composite)叶子类(leaf)继承组件类, 客户类(client)直接调用最顶层的组合类(composite)即可.

具体方法:

1. 组件类(component), 包含组合类(composite)和叶子类(leaf)所使用的方法, 即树形结构的一个结点, 使用抽象类(abstract).

如果未定义而使用, 则会抛出异常(exception).

/**
 * @time 2014年7月4日
 */
package composite;

/**
 * @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();
	}
}

2. 叶子类(leaf)继承组件类(component), 实现特定的输出方法.

/**
 * @time 2014年7月4日
 */
package composite;

/**
 * @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());
	}

}

3. 组合类(composite)继承组件类, 实现所需的方法, 可以添加某些叶子类(leaf)作为子节点.

/**
 * @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();
		}
	}

}

4. 客户类(client)直接调用, 最顶层的组合类(composite)即可.

/**
 * @time 2014年7月4日
 */
package composite;

/**
 * @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();
	}

}

5. 测试:

/**
 * @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.printMenu();
	}

}

6. 输出:

ALL MENUS, All menus combined
--------------------

PANCAKE HOUSE MENU, Breakfast
--------------------
 K&B‘s Pancake Breakfast(v), 2.99
    -- Pancakes with scrambled eggs, and toast
 Regular Pancake Breakfast, 2.99
    -- Pancakes with fried eggs, sausage
 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

DINER MENU, Lunch
--------------------
 Vegetarian BLT(v), 2.99
    -- (Fakin‘) Bacon with lettuce & tomato on whole wheat
 BLT, 2.99
    -- Bacon with lettuce & tomato on whole wheat
 Soup of the day, 3.29
    -- A bowl of the soup of the day, with a side of potato salad
 Hotdog, 3.05
    -- A hot dog, with saurkraut, relish, onions, topped with cheese
 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

DESSERT MENU, Dessert course!
--------------------
 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

CAFE MENU, Dinner
--------------------
 Veggie Burger and Air Fries(v), 3.99
    -- Veggie burger on a whole wheat bun, lettuce, tomato, and fries
 Soup of the day, 3.69
    -- A cup of the soup of the day, with a side salad
 Burrito(v), 4.29
    -- A large burrito, with whole pinto beans, salsa, guacamole

COFFEE MENU, Stuff to go with your afternoon coffee
--------------------
 Coffee Cake(v), 1.59
    -- Crumbly cake topped with cinnamon and walnuts
 Bagel, 0.69
    -- Flavors include sesame, poppyseed, cinnamon raisin, pumpkin
 Biscotti(v), 0.89
    -- Three almond or hazelnut biscotti cookies

设计模式 - 组合模式(composite pattern) 详解,布布扣,bubuko.com

时间: 2024-10-19 01:15:01

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

设计模式 - 组合模式(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

设计模式 - 外观模式(facade pattern) 详解

外观模式(facade pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy 外观模式(facade pattern): 提供了一个统一的接口, 用来访问子系统中的一群接口. 外观定义了一个高层接口, 让子系统更容易使用. 外观模式包含三个部分: 1. 子系统: 子类, 单个复杂子类 或 多个子类; 2. 外观(facade)类: 把子系统设计的更加容易使用; 3. 客户: 只需要调用外观类. 与适配器模式(adapter pattern)的

设计模式 - 策略模式(Strategy Pattern) 详解

策略模式(Strategy Pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26577879 本文版权所有, 禁止转载, 如有需要, 请站内联系. 策略模式: 定义了算法族, 分别封装起来, 让它们之间可以相互替换, 此模式让算法的变化独立于使用算法的客户. 对于父类的子类族需要经常扩展新的功能, 为了使用父类比较灵活的添加子类, 把父类的行为写成接口(interface)的形式; 使用set()方法,

设计模式 - 状态模式(state pattern) 详解

状态模式(state pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy 状态模式(state pattern): 允许对象在内部状态改变时改变它的行为, 对象看起来好像修改了它的类. 建立Context类, 包含多个具体状态(concrete state)类的组合, 根据状态的不同调用具体的方法, state.handle(), 包含set\get方法改变状态. 状态接口(state interface), 包含抽象方法handle(),

设计模式 - 单件模式(singleton pattern) 详解

单件模式(singleton pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy/article/details/28595349 单件模式(singleton pattern) : 确保一个类只有一个实例, 并提供一个全局访问点. 单价模式包括3个部分: 私有构造器, 静态变量, 静态方法. 具体方法: 1. 标准的单例模式: /** * @time 2014.6.5 */ package singleton; /** * @author

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

迭代器模式(iterator pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy 迭代器模式(iterator pattern) : 提供一种方法顺序访问一个聚合对象中的各个元素, 而又不暴露其内部的表示; 建立迭代器接口(iterator interface), 包含hasNext()方法和next()方法; 不同聚合对象的具体的迭代器(concrete iterator), 继承(implements)迭代器接口(iterator in

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

命令模式(command pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy 命令模式: 将请求封装成对象, 以便使用不同的请求\队列\日志来参数化其他对象. 命令模式也支持可撤销操作. 命令模式: 调用者(Invoker); 命令(Command): 可执行方法(execute), 具体命令(Concrete Command); 接受者(Receiver): 调用命令(Set Command); 具体方法: 1. 具体对象. /** *

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

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

设计模式 - 装饰者模式(Decorator Pattern) 详解

装饰者模式(Decorator Pattern) 详解 本文地址: http://blog.csdn.net/caroline_wendy/article/details/26707033 装饰者模式(Decorator Pattern):动态地将责任附加到对象上. 若要扩展功能, 装饰者提供了比继承更有弹性的替代方案. 使用方法: 1. 首先创建组件(Component)父类, 所有类,具体组件(Concrete Component)和装饰者(Decorator)都属于这一类型, 可以进行扩展