组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。 package composite; //公司类 抽象类或接口 abstract class Company { protected String name; public Company(String name) { this.name = name; } public abstract void add(Company c);//增加 public abstract void Remove(Company c);//移除 public abstract void Display(int depth);//显示 public abstract void LineOfDuty();//履行职责 } //具体公司实现类 实现接口 树枝节点 public class ConcreteCompany extends Company{ private ArrayList<Company> children = new ArrayList<Company>(); public ConcreteCompany(String name) { super(name); } @Override public void LineOfDuty() { for(Company component :children) { component.LineOfDuty(); } } @Override public void Remove(Company c) { children.remove(c); } @Override public void add(Company c) { children.add(c); } @Override public void Display(int depth) { System.out.println("------" + depth + " " + name); for(Company component :children) { component.Display(depth + 1); } } } public class FinanceDepartment extends Company{ public FinanceDepartment(String name) { super(name); } @Override public void Display(int depth) { System.out.println("------" + depth + " " + name); } @Override public void LineOfDuty() { System.out.println("公司财务收支管理 " + name); } @Override public void Remove(Company c) { } @Override public void add(Company c) { } } //人力资源部与财务部类 树叶节点 public class HRDepartment extends Company{ public HRDepartment(String name) { super(name); } @Override public void Display(int depth) { System.out.println("------" + depth + " " + name); } @Override public void LineOfDuty() { System.out.println("员工招聘培训管理 " + name); } @Override public void Remove(Company c) { } @Override public void add(Company c) { } } public class TestComposite { public static void main(String[] args) { ConcreteCompany root = new ConcreteCompany("北京总公司"); root.add(new HRDepartment("总公司人力资源部")); root.add(new FinanceDepartment("总公司财务部")); ConcreteCompany comp = new ConcreteCompany("上海华东分公司"); comp.add(new HRDepartment("华东分公司人力资源部")); comp.add(new FinanceDepartment("华东分公司财务部")); root.add(comp); ConcreteCompany comp1 = new ConcreteCompany("南京办事处"); comp1.add(new HRDepartment("南京办事处人力资源部")); comp1.add(new FinanceDepartment("南京办事处财务部")); comp.add(comp1); ConcreteCompany comp2 = new ConcreteCompany("杭州办事处"); comp2.add(new HRDepartment("杭州办事处人力资源部")); comp2.add(new FinanceDepartment("杭州办事处财务部")); comp.add(comp2); System.out.println("结构图:"); root.Display(1); System.out.println("职责:"); root.LineOfDuty(); } }