- 设计模式教程
- 设计模式 - 首页
- 设计模式 - 概述
- 设计模式 - 工厂模式
- 抽象工厂模式
- 设计模式 - 单例模式
- 设计模式 - 建造者模式
- 设计模式 - 原型模式
- 设计模式 - 适配器模式
- 设计模式 - 桥接模式
- 设计模式 - 过滤器模式
- 设计模式 - 组合模式
- 设计模式 - 装饰器模式
- 设计模式 - 外观模式
- 设计模式 - 享元模式
- 设计模式 - 代理模式
- 责任链模式
- 设计模式 - 命令模式
- 设计模式 - 解释器模式
- 设计模式 - 迭代器模式
- 设计模式 - 中介者模式
- 设计模式 - 备忘录模式
- 设计模式 - 观察者模式
- 设计模式 - 状态模式
- 设计模式 - 空对象模式
- 设计模式 - 策略模式
- 设计模式 - 模板模式
- 设计模式 - 访问者模式
- 设计模式 - MVC模式
- 业务代表模式
- 组合实体模式
- 数据访问对象模式
- 前端控制器模式
- 拦截过滤器模式
- 服务定位器模式
- 传输对象模式
- 设计模式资源
- 设计模式 - 问答
- 设计模式 - 快速指南
- 设计模式 - 有用资源
- 设计模式 - 讨论
设计模式 - 组合模式
组合模式用于我们需要以类似于单个对象的方式处理一组对象的情况。组合模式将对象组合成树形结构,以表示部分以及整体层次结构。这种设计模式属于结构模式,因为它创建了对象组的树形结构。
这种模式创建一个包含其自身对象组的类。此类提供修改其相同对象组的方法。
我们将通过以下示例演示组合模式的使用,在该示例中,我们将展示组织的员工层次结构。
实现
我们有一个`Employee`类,它充当组合模式参与者类。我们的演示类`CompositePatternDemo`将使用`Employee`类来添加部门级别层次结构并打印所有员工。
步骤1
创建包含`Employee`对象列表的`Employee`类。
Employee.java
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
// constructor
public Employee(String name,String dept, int sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList<Employee>();
}
public void add(Employee e) {
subordinates.add(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
public String toString(){
return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary+" ]");
}
}
步骤2
使用`Employee`类创建并打印员工层次结构。
CompositePatternDemo.java
public class CompositePatternDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John","CEO", 30000);
Employee headSales = new Employee("Robert","Head Sales", 20000);
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);
Employee clerk1 = new Employee("Laura","Marketing", 10000);
Employee clerk2 = new Employee("Bob","Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);
CEO.add(headSales);
CEO.add(headMarketing);
headSales.add(salesExecutive1);
headSales.add(salesExecutive2);
headMarketing.add(clerk1);
headMarketing.add(clerk2);
//print all employees of the organization
System.out.println(CEO);
for (Employee headEmployee : CEO.getSubordinates()) {
System.out.println(headEmployee);
for (Employee employee : headEmployee.getSubordinates()) {
System.out.println(employee);
}
}
}
}
步骤3
验证输出。
Employee :[ Name : John, dept : CEO, salary :30000 ] Employee :[ Name : Robert, dept : Head Sales, salary :20000 ] Employee :[ Name : Richard, dept : Sales, salary :10000 ] Employee :[ Name : Rob, dept : Sales, salary :10000 ] Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ] Employee :[ Name : Laura, dept : Marketing, salary :10000 ] Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
广告