实现上来说是这样的。区别在于聚合的话部分的实例可以独立于整体的实例存在,组合的话部分的实例不可以独立于整体的实例存在,整体实例消失部分实例也会消失。
聚合的例子——部门和员工,部门就算没了员工也还是可以存在:
public class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public class Department {
private List employees;
public Department() {
this.employees = new ArrayList(); // 初始化的时候员工列表可以为空
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public void removeEmployee(Employee employee) {
employees.remove(employee);
}
public List getEmployees() {
return employees;
}
}
组合的例子——引擎和汽车,引擎是汽车的一部分,同时引擎不能创建自己的实例,必须由汽车创建:
public class Engine {
private boolean isRunning;
public void start() {
isRunning = true;
}
public void stop() {
isRunning = false;
}
public boolean isRunning() {
return isRunning;
}
}
public class Car {
private Engine engine;
public Car() {
this.engine = new Engine(); // 引擎只能在汽车创建实例的时候也创建实例
}
public void startEngine() {
engine.start();
}
public void stopEngine() {
engine.stop();
}
public boolean isEngineRunning() {
return engine.isRunning();
}
}