概念理解
组合模式用来表示整体和部分的结构,是一种结构型模式。对于客户端而言,整体和部分开放的是同一个接口,调用起来并没有不同。换种说法,一个对象和一组对象对于客户端而言,使用方式是一致的。
实例说明
组合模式的典型表示方式是树形结构,实例有很多,比如文件系统,网站菜单,公司和部门之间的关系,员工领导和下属的关系。现在考虑员工和下属的关系,实现起来非常简单:不管是领导还是员工,都使用同一个类雇员,雇员中有名字,薪水,部门,和管理的下属员工。底层员工的下属员工列表为空,并不影响调用。
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinate;
public Employee(String name, String dept, int salary) {
this.name = name;
this.dept = dept;
this.salary = salary;
subordinate = new ArrayList<Employee>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public List<Employee> getSubordinate() {
return subordinate;
}
public void setSubordinate(List<Employee> subordinate) {
this.subordinate = subordinate;
}
public void addEmployee(Employee e) {
this.subordinate.add(e);
}
@Override
public String toString() {
return "name=" + name + ",dept=" + dept + ",salary=" + salary;
}
}
public class App {
public static void main(String[] args) {
Employee chief = initEmployee();
printEmployee(chief);
}
public static void printEmployee(Employee e){
System.out.println(e.toString());
List<Employee> subordinates = e.getSubordinate();
for(int i =0;i<subordinates.size();i++){
printEmployee(subordinates.get(i));
}
}
public static Employee initEmployee() {
Employee chief = new Employee("SAM", "Finance", 10000);
Employee leader = new Employee("tom", "Finance", 7000);
Employee amy = new Employee("amy", "Finance", 4000);
Employee sary = new Employee("sary", "Finance", 4000);
chief.addEmployee(leader);
chief.addEmployee(sary);
leader.addEmployee(amy);
return chief;
}
}
代码实例参见:https://github.com/jxl198/designPattern/tree/master/composite