软考 组合设计模式
组合设计模式(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(); // 打印整个组织结构}
}