组合模式:将对象组合成树形结构。
案例:公司管理。一个公司可以分总公司和分公司,无论是总公司还是分公司都有自己的部门,如人力资源管理部门、财务部门。分公司可以建立自己在不同地域的办事处。请使用组合模式打印出某个公司的结构。
package Composite;abstract class Company {private String name;public Company(String name) {this.name = name;}public String getName() {return name;}public abstract void add(Company company);public abstract void remove(Company company);public abstract void display(int depth);public abstract void lineOfDuty();}
package Composite;import java.util.ArrayList;
import java.util.List;public class ConcreteCompanty extends Company{private List<Company> children = new ArrayList<>();public ConcreteCompanty(String name) {super(name);}@Overridepublic void add(Company company) {children.add(company);}@Overridepublic void remove(Company company) {children.remove(company);}@Overridepublic void display(int depth) {for(int i=0;i<depth;i++)System.out.print("-");System.out.println(this.getName());for(Company company : children) {company.display(depth + 2);}}@Overridepublic void lineOfDuty() {}
}
package Composite;public class FinanceDepartment extends Company{public FinanceDepartment(String name) {super(name);}@Overridepublic void add(Company company) {}@Overridepublic void remove(Company company) {}@Overridepublic void display(int depth) {for(int i=0;i<depth;i++)System.out.print("-");System.out.println(this.getName());}@Overridepublic void lineOfDuty() {}
}
package Composite;public class HRDepartment extends Company{public HRDepartment(String name) {super(name);}@Overridepublic void add(Company company) {}@Overridepublic void remove(Company company) {}@Overridepublic void display(int depth) {for(int i=0;i<depth;i++)System.out.print("-");System.out.println(this.getName());}@Overridepublic void lineOfDuty() {}
}
package Composite;public class Client {public static void main(String[] args) {ConcreteCompanty root = new ConcreteCompanty("总公司");root.add(new HRDepartment("总公司人力资源部"));root.add(new FinanceDepartment("总公司财务部"));ConcreteCompanty comp = new ConcreteCompanty("分公司1");comp.add(new HRDepartment("分公司1人力资源部"));comp.add(new FinanceDepartment("分公司1财务部"));ConcreteCompanty comp1 = new ConcreteCompanty("分公司1办事处A");comp1.add(new HRDepartment("分公司1办事处人力资源部"));comp1.add(new FinanceDepartment("分公司1办事处财务部"));ConcreteCompanty comp2 = new ConcreteCompanty("分公司1办事处B");comp2.add(new HRDepartment("分公司1办事处B人力资源部"));comp2.add(new FinanceDepartment("分公司1办事处B财务部"));comp.add(comp1);comp.add(comp2);root.add(comp);ConcreteCompanty compt = new ConcreteCompanty("分公司2");compt.add(new HRDepartment("分公司2人力资源部"));compt.add(new FinanceDepartment("分公司2财务部"));root.add(compt);root.display(1);}
}