組合設計模式(Composite Pattern)是結構型設計模式之一,它的核心思想是將對象組合成樹形結構來表示“部分-整體”的層次結構,使得用戶對單個對象和組合對象的使用具有一致性。
主要概念:
-
組件(Component):定義一個接口,用于訪問和操作所有的對象(包括葉子節點和組合節點)。
-
葉子節點(Leaf):表示樹的葉子節點,沒有子節點,繼承組件接口并實現具體行為。
-
組合節點(Composite):表示樹中的分支節點,可以包含葉子節點或者其他組合節點,同樣繼承組件接口并實現具體行為,同時還會提供對子節點的管理功能(例如添加、刪除)。private List<OrganizationComponent> components = new ArrayList<>();? ? ? ? ? ? ? ? ? ? ? ?public void addComponent(OrganizationComponent component) {
? ? ? ? components.add(component);
? ? }?
@Override
? ? public void showDetails() {
? ? ? ? System.out.println("Department: " + name);
? ? ? ? for (OrganizationComponent component : components) {
? ? ? ? ? ? component.showDetails();
? ? ? ? }
? ? }
適用場景:
-
當需要表示對象的“部分-整體”層次結構時。
-
客戶端希望統一對待單個對象和組合對象時。
-
需要在系統中處理樹形結構的數據時,比如圖形界面中樹形結構的布局。
示例:
假設我們有一個組織結構的系統,包含員工(葉子節點)和部門(組合節點),每個部門下可能包含多個員工或子部門。
// 組件接口
interface OrganizationComponent {void showDetails();
}// 葉子節點(員工)
class Employee implements OrganizationComponent {private String name;public Employee(String name) {this.name = name;}@Overridepublic void showDetails() {System.out.println("Employee: " + name);}
}// 組合節點(部門)
class Department implements OrganizationComponent {private String name;private List<OrganizationComponent> components = new ArrayList<>();public Department(String name) {this.name = name;}public void addComponent(OrganizationComponent component) {components.add(component);}@Overridepublic void showDetails() {System.out.println("Department: " + name);for (OrganizationComponent component : components) {component.showDetails();}}
}使用
public class CompositePatternDemo {public static void main(String[] args) {OrganizationComponent emp1 = new Employee("Alice");OrganizationComponent emp2 = new Employee("Bob");Department dept1 = new Department("HR");dept1.addComponent(emp1);dept1.addComponent(emp2);OrganizationComponent emp3 = new Employee("Charlie");Department dept2 = new Department("Finance");dept2.addComponent(emp3);Department headOffice = new Department("Head Office");headOffice.addComponent(dept1);headOffice.addComponent(dept2);headOffice.showDetails(); // 打印整個組織結構}
}輸出
public class CompositePatternDemo {public static void main(String[] args) {OrganizationComponent emp1 = new Employee("Alice");OrganizationComponent emp2 = new Employee("Bob");Department dept1 = new Department("HR");dept1.addComponent(emp1);dept1.addComponent(emp2);OrganizationComponent emp3 = new Employee("Charlie");Department dept2 = new Department("Finance");dept2.addComponent(emp3);Department headOffice = new Department("Head Office");headOffice.addComponent(dept1);headOffice.addComponent(dept2);headOffice.showDetails(); // 打印整個組織結構}
}