HeadFirst设计模式之组合模式
一、
1.The Composite Pattern allows us to build structures of objects in the form of trees that contain both compositions of objects and individual objects as nodes.
2.Using a composite structure,we can apply the same operations over both composites and individual objects. In other words, in most cases we can ignore the differences between compositions of objects and individual objects.
3.The Composite Pattern allows you to compose objects into tree structures to represent part-whole hierarchies. Composite
lets clients treat individual objects and compositions of objects uniformly.
4
.
5.
6.

7.
8.
9.
二、
1.
 package headfirst.designpatterns.composite.menu;
 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.
package headfirst.designpatterns.composite.menu; import java.util.Iterator;
import java.util.ArrayList; 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 (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();
}
}
}
3.
 package headfirst.designpatterns.composite.menu;
 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());
     }
 }
4.
 package headfirst.designpatterns.composite.menu;
 public class Waitress {
     MenuComponent allMenus;
     public Waitress(MenuComponent allMenus) {
         this.allMenus = allMenus;
     }
     public void printMenu() {
         allMenus.print();
     }
 }
5.
 package headfirst.designpatterns.composite.menu; 
 public class MenuTestDrive {
     public static void main(String args[]) {
         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 of 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();
     }
 }
三、带Iterator
1.
 package headfirst.designpatterns.composite.menuiterator;
 import java.util.*;
 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 abstract Iterator<MenuComponent> createIterator();
     public void print() {
         throw new UnsupportedOperationException();
     }
 }
2.
 package headfirst.designpatterns.composite.menuiterator;
 import java.util.*;
 public class CompositeIterator implements Iterator<MenuComponent> {
     Stack<Iterator<MenuComponent>> stack = new Stack<Iterator<MenuComponent>>();
     public CompositeIterator(Iterator<MenuComponent> iterator) {
         stack.push(iterator);
     }
     public MenuComponent next() {
         if (hasNext()) {
             Iterator<MenuComponent> iterator = stack.peek();
             MenuComponent component = iterator.next();
             stack.push(component.createIterator());
             return component;
         } else {
             return null;
         }
     }
     public boolean hasNext() {
         if (stack.empty()) {
             return false;
         } else {
             Iterator<MenuComponent> iterator = stack.peek();
             if (!iterator.hasNext()) {
                 stack.pop();
                 return hasNext();
             } else {
                 return true;
             }
         }
     }
     /*
      * No longer needed as of Java 8
      *
      * (non-Javadoc)
      * @see java.util.Iterator#remove()
      *
     public void remove() {
         throw new UnsupportedOperationException();
     }
     */
 }
3.
 package headfirst.designpatterns.composite.menuiterator;
 import java.util.Iterator;
 public class NullIterator implements Iterator<MenuComponent> {
     public MenuComponent next() {
         return null;
     }
     public boolean hasNext() {
         return false;
     }
     /*
      * No longer needed as of Java 8
      *
      * (non-Javadoc)
      * @see java.util.Iterator#remove()
      *
     public void remove() {
         throw new UnsupportedOperationException();
     }
     */
 }
4.
package headfirst.designpatterns.composite.menuiterator; import java.util.Iterator;
import java.util.ArrayList; public class Menu extends MenuComponent {
Iterator<MenuComponent> iterator = null;
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 Iterator<MenuComponent> createIterator() {
if (iterator == null) {
iterator = new CompositeIterator(menuComponents.iterator());
}
return iterator;
} 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 = iterator.next();
menuComponent.print();
}
}
}
5.
 package headfirst.designpatterns.composite.menuiterator;
 import java.util.Iterator;
 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 Iterator<MenuComponent> createIterator() {
         return new NullIterator();
     }
     public void print() {
         System.out.print("  " + getName());
         if (isVegetarian()) {
             System.out.print("(v)");
         }
         System.out.println(", " + getPrice());
         System.out.println("     -- " + getDescription());
     }
 }
6.
 package headfirst.designpatterns.composite.menuiterator;
 import java.util.Iterator;
 public class Waitress {
     MenuComponent allMenus;
     public Waitress(MenuComponent allMenus) {
         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 = iterator.next();
             try {
                 if (menuComponent.isVegetarian()) {
                     menuComponent.print();
                 }
             } catch (UnsupportedOperationException e) {}
         }
     }
 }
7.
 package headfirst.designpatterns.composite.menuiterator;
 public class MenuTestDrive {
     public static void main(String args[]) {
         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 of course!");
         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",
             "A medly of 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));
         Waitress waitress = new Waitress(allMenus);
         waitress.printVegetarianMenu();
     }
 }
HeadFirst设计模式之组合模式的更多相关文章
- C#设计模式(10)——组合模式(Composite Pattern)
		
一.引言 在软件开发过程中,我们经常会遇到处理简单对象和复合对象的情况,例如对操作系统中目录的处理就是这样的一个例子,因为目录可以包括单独的文件,也可以包括文件夹,文件夹又是由文件组成的,由于简单对象 ...
 - c++设计模式15 --组合模式
		
今天研究了一下设计模式15 组合模式 本人是菜鸟一枚,所以一开始完全不懂组合究竟是什么意思.先上图一张,树形结构图: 文档说,如果想做出这样的结构,通常考虑组合模式.那是为什么呢?现在让我们看一下组合 ...
 - 乐在其中设计模式(C#) - 组合模式(Composite Pattern)
		
原文:乐在其中设计模式(C#) - 组合模式(Composite Pattern) [索引页][源码下载] 乐在其中设计模式(C#) - 组合模式(Composite Pattern) 作者:weba ...
 - JavaScript设计模式之----组合模式
		
javascript设计模式之组合模式 介绍 组合模式是一种专门为创建Web上的动态用户界面而量身制定的模式.使用这种模式可以用一条命令在多个对象上激发复杂的或递归的行为.这可以简化粘合性代码,使其更 ...
 - C#设计模式(10)——组合模式(Composite Pattern)(转)
		
一.引言 在软件开发过程中,我们经常会遇到处理简单对象和复合对象的情况,例如对操作系统中目录的处理就是这样的一个例子,因为目录可以包括单独的文件,也可以包括文件夹,文件夹又是由文件组成的,由于简单对象 ...
 - C#设计模式:组合模式(Composite Pattern)
		
一,C#设计模式:组合模式(Composite Pattern) using System; using System.Collections.Generic; using System.Linq; ...
 - 【GOF23设计模式】组合模式
		
来源:http://www.bjsxt.com/ 一.[GOF23设计模式]_组合模式.树状结构.杀毒软件架构.JUnite底层架构.常见开发场景 package com.test.composite ...
 - 设计模式:组合模式(Composite)
		
定 义:将对象组合树形结构以表示“部分-整体”的层次结构.组合模式使得用户对单个对象和组合对象使用具有一致性. 结构图: Component类: abstract class Component ...
 - [设计模式] 8 组合模式 Composite
		
DP书上给出的定义:将对象组合成树形结构以表示“部分-整体”的层次结构.组合使得用户对单个对象和组合对象的使用具有一致性.注意两个字“树形”.这种树形结构在现实生活中随处可见,比如一个集团公司,它有一 ...
 
随机推荐
- MyEclipse导入ant项目——Java编程思想
			
北门煎饼东门串儿: <JAVA编程思想(Think in Java)>一书中提供了大量源代码,可是项目是用ant构建的.对于用惯了eclipse,netbeans等IDE的同学们可能有些手 ...
 - Science论文"Clustering by fast search and find of density peaks"学习笔记
			
"Clustering by fast search and find of density peaks"是今年6月份在<Science>期刊上发表的的一篇论文,论文中 ...
 - 解决DB2事物日志满、扩充表字段长度和表空间的命令
			
解决DB2事物日志满.扩充表字段长度和表空间的命令 转:http://blog.sina.com.cn/s/blog_4c0137d10100bb5r.html 一.通常我们在使用db2导入数据或进行 ...
 - css3选择器二
			
在HTML中,通过各种各样的属性可以给元素增加很多附加的信息,了解和掌握css3一些的选择器,是很有必要的. :enabled 和 :disabled选择器表单元素有可用(“:enabled”)和不可 ...
 - AjaxFileUpload Firefox 不工作异常 (zero-width space characters from a JavaScript string)
			
Firefox 返回的提示报错parse error (Chrome 和 IE正常) 打印出来返回的字符串,目测正常 将字符串放入notepad++, 转换字符集为ANSI 发现多出了欧元符号 通过j ...
 - Linux 服务器如何修改 DNS
			
个人一直用的阿里云的ECS,在配置环境的时候就想着修改一下默认的 DNS,听说阿里云自己的 DNS 速度和稳定性都不错,所以就将默认的 DNS 修改成了阿里云的DNS,并一直稳定使用,下面给出修改方法 ...
 - CorelDRAW 文件实用工具 CDRTools 2
			
随着 CorelDRAW 更新脚步越来越频繁,版本之间兼容性问题越来越突出,特别是跨版本之间打开会有很多问题,比如:文字跑位.透镜变向.位图出错.颜色改变,甚至会造成文件损坏.最好的办法就是哪一个版本 ...
 - IE10用video标签播放本地mp4文件失败的解决办法
			
1. 首先用“格式工厂”将要播放的视频文件按照“AVC高质量与大小”转换为要求格式的mp4文件: 2. 设置IIS7.5,添加mp4的MIME类型,步骤如下: 1.打开IIS管理器(运行inetmgr ...
 - Oracle修改表空间大小
			
在向orale数据库导入数据的时候报 ORA-01658: 无法为表空间 XXX中的段创建 INITIAL 区错误. Oracle我在创建表空间的时候初始化大小为200M,当数据库中数据量达到这个值, ...
 - Head First设计模式悟道
			
暂时包括 策略模式,观察者,装饰模式,工厂模式,抽象工厂模式,后续会继续补充中,纯属个人总结用,不喜勿喷, 源代码见: 传送门 public class NYPizzaIngredientFactor ...