一、基本介紹
組合模式(結構型):又叫部分-整體模式,它是一種将對象組合成樹狀的層次結構的模式,用來表示“部分-整體”的關系,使使用者對單個對象群組合對象具有一緻的通路性。
二、包含角色
1.抽象構件角色:它的主要作用是為樹葉構件和樹枝構件聲明公共接口,并實作它們的預設行為。
2.樹葉構件角色:是組合中的葉節點對象,它沒有子節點,是樹枝構件的子節點。
3.樹枝構件角色:是組合中的分支節點對象,它有子節點,它的主要作用是存儲和管理子部件
三、案例及UML類圖
案例說明:
菜單--樹枝,菜品—樹葉,菜單下有多個菜品,而菜品沒有子菜品。要使使用者對菜品和菜單的操作都是一緻的接口。
UML類圖:
類MenuComponent:
public abstract class MenuComponent {
protected String name;
protected String description;
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public void add(MenuComponent menuComponent) {
throw new RuntimeException("不支援該操作!");
}
public void remove(MenuComponent menuComponent) {
throw new RuntimeException("不支援該操作!");
}
public double getPrice() {
throw new RuntimeException("不支援該操作!");
}
public boolean isVegetarian() {
throw new RuntimeException("不支援該操作!");
}
public abstract void print();
}
說明:定義菜單和菜品的操作接口,并顯示其預設方法,抽象建構角色。
類MenuItem:
public class MenuItem extends MenuComponent {
private double price;
//是否售完
private boolean egetarian;
public MenuItem(String name,String description,double price, boolean egetarian) {
this.name = name;
this.description = description;
this.price = price;
this.egetarian = egetarian;
}
@Override
public double getPrice() {
return price;
}
@Override
public boolean isVegetarian() {
return egetarian;
}
@Override
public void print() {
System.out.println("名字:"+name+",描述:"+description+",價格:"+price+",已售完:"+egetarian);
}
}
說明:菜品,樹葉構件角色,定義菜品的屬性和重寫菜品自己的方法。
類Menu:
public class Menu extends MenuComponent {
private List<MenuComponent> menuComponents = new ArrayList<>();
public Menu(String name,String description) {
this.name = name;
this.description = description;
}
@Override
public void add(MenuComponent menuComponent) {
menuComponents.add(menuComponent);
}
@Override
public void remove(MenuComponent menuComponent) {
menuComponents.remove(menuComponent);
}
@Override
public void print() {
System.out.println("目前菜單名字是:"+name+",描述是:"+description);
System.out.println("--------------------");
for(MenuComponent menuComponent : menuComponents) {
menuComponent.print();
}
}
}
說明:菜單,樹葉構件角色,菜單下包含有菜單或菜品數組,定義菜單自己的屬性和重寫菜單自己的方法。
類ComponentTest:
public class ComponentTest {
public static void main(String[] args) {
MenuComponent menu = new Menu("精品菜","本店精選!");
MenuComponent menuItem1 = new MenuItem("開水白菜","好吃的白菜",999,false);
menu.add(menuItem1);
menu.print();
}
}
說明:測試及用戶端類。
四、适用場景
1.使用者需要屏蔽單個對象群組合對象之間的不同,讓使用者使用同一個接口操作。
2.适用于呈現樹葉和樹枝結構(樹形結構)的業務場景,如檔案和檔案夾,如XML解析,公司部門等。