现在的位置: 首页 > 综合 > 正文

组合模式(Composite Pattern)(二):HeadFirst中使用组合设计菜单

2018年02月04日 ⁄ 综合 ⁄ 共 2385字 ⁄ 字号 评论关闭

一、问题描述

使用组合模式为餐厅设计菜单,使服务员Waitress可以很方便地使用菜单。

二、类图

三、代码实现

1.(Component角色)MenuComponent

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角色)MenuItem

public class MenuItem extends MenuComponent
{
	String name;
	String description;
	boolean vegetarian;
	double price;

	public MenuItem(String name, String description, boolean vegetarian,double price)
	{
		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角色)Menu

public class Menu extends MenuComponent
{
	ArrayList<MenuComponent> menuComponents = new ArrayList<MenuComponent>();
	String name;
	String description;

	public Menu(String name, String description)
	{
		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  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 iterator = menuComponents.iterator();
		while (iterator.hasNext())
		{
			MenuComponent menuComponent = (MenuComponent) iterator.next();
			menuComponent.print();
		}
	}
}

4.(Client角色)Waitress

public class Waitress
{
	MenuComponent allMenus;

	public Waitress(MenuComponent allMenus)
	{
		this.allMenus = allMenus;
	}

	public void printMenu()
	{
		allMenus.print();
	}
}

5.测试略

转载请注明出处:http://blog.csdn.net/jialinqiang/article/details/8947935

抱歉!评论已关闭.