组合模式——Head First Design Patterns

来源:互联网 发布:新闻资讯软件下载 编辑:程序博客网 时间:2024/06/06 10:03

定义:组合模式将对象组合成树形结构以表示“部分—整体”的层次关系,这使得使用者处理单个对象和组合对象时具有一致性

 

使用场景:当单个对象和组合对象需要对外提供类似的接口时

 

类图:

代码样例:

package headfirst.composite.menu;import java.util.Iterator;import java.util.ArrayList;public class Menu extends MenuComponent {ArrayList menuComponents = new ArrayList();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 iterator = menuComponents.iterator();while (iterator.hasNext()) {MenuComponent menuComponent = (MenuComponent)iterator.next();menuComponent.print();}}}


 

package headfirst.composite.menu;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 void print() {throw new UnsupportedOperationException();}}


 

package headfirst.composite.menu;import java.util.Iterator;import java.util.ArrayList;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());}}


 

package headfirst.composite.menu;import java.util.Iterator;  public class Waitress {MenuComponent allMenus; public Waitress(MenuComponent allMenus) {this.allMenus = allMenus;} public void printMenu() {allMenus.print();}}


 

优点:1)简化对外的使用方式

缺点:1

 

类似的设计模式:

 

配套的内功心法:1

0 0
原创粉丝点击