什么是组合模式。用java代码写一个案例
时间: 2024-02-29 18:53:23 浏览: 65
组合模式是一种结构型设计模式,它允许将对象组合成树形结构来表示“部分-整体”的层次结构。组合模式使得用户可以像对待单个对象一样对待整个组合对象。
以下是一个使用组合模式的简单示例,它表示了一个组织结构,包括公司、部门和员工。每个公司可以包含多个部门,每个部门可以包含多个员工。
```java
interface OrganizationUnit {
void print();
}
class Company implements OrganizationUnit {
private List<OrganizationUnit> departments = new ArrayList<>();
public void addDepartment(OrganizationUnit department) {
departments.add(department);
}
@Override
public void print() {
System.out.println("Company");
for (OrganizationUnit unit : departments) {
unit.print();
}
}
}
class Department implements OrganizationUnit {
private List<OrganizationUnit> employees = new ArrayList<>();
public void addEmployee(OrganizationUnit employee) {
employees.add(employee);
}
@Override
public void print() {
System.out.println("Department");
for (OrganizationUnit unit : employees) {
unit.print();
}
}
}
class Employee implements OrganizationUnit {
private String name;
public Employee(String name) {
this.name = name;
}
@Override
public void print() {
System.out.println("Employee: " + name);
}
}
public class CompositePatternExample {
public static void main(String[] args) {
Company company = new Company();
Department department1 = new Department();
department1.addEmployee(new Employee("John"));
department1.addEmployee(new Employee("Jane"));
Department department2 = new Department();
department2.addEmployee(new Employee("Bob"));
department2.addEmployee(new Employee("Alice"));
company.addDepartment(department1);
company.addDepartment(department2);
company.print();
}
}
```
输出:
```
Company
Department
Employee: John
Employee: Jane
Department
Employee: Bob
Employee: Alice
```
阅读全文