0-前言
组合模式定义(Composite):将对象组合成树形结构以表示“部分-整体”的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有一致性;
1-实现
1-1、简单UML图:
1-2、代码实现:
//1、抽象父类(公司父类)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(); //履行部门职责}//2、枝节点(具体公司类)class ConcreteCompany extends Company { private ListchildrenList = new ArrayList(); public ConcreteCompany(String companyname) { super(companyname); } @Override public void Add(Company c) { childrenList.add(c); } @Override public void Remove(Company c) { childrenList.remove(c); } @Override public void Display(int depth) { for(int i=0;i<depth;i++) { System.out.print('-'); } System.out.print(Name + '\n'); for (int i = 0;i<childrenList.size();i++) { childrenList.get(i).Display(depth + 2); } } @Override public void LineofDuty() { for (int i = 0;i<childrenList.size();i++) { childrenList.get(i).LineofDuty(); } } }//3-1、叶子节点(具体公司部门类--人力资源部)class HRDepartment extends Company { public HRDepartment(String companyname) { super(companyname); } @Override public void Add(Company c) { } @Override public void Remove(Company c) { } @Override public void Display(int depth) { for(int i=0;i<depth;i++) { System.out.print('-'); } System.out.print(Name + '\n'); } @Override public void LineofDuty() { System.out.println(Name + ": 招聘员工"); } }//3-2、叶子节点(具体公司部门类--财务部)class FinanceDepartment extends Company { public FinanceDepartment(String companyname) { super(companyname); } @Override public void Add(Company c) { } @Override public void Remove(Company c) { } @Override public void Display(int depth) { for(int i=0;i<depth;i++) { System.out.print('-'); } System.out.print(Name + '\n'); } @Override public void LineofDuty() { System.out.println(Name + ": 发放工资"); }
客户端:
ConcreteCompany root = new ConcreteCompany("深圳总公司"); root.Add(new HRDepartment("深圳总公司人力资源部")); root.Add(new FinanceDepartment("深圳总公司财务部")); ConcreteCompany cp1 = new ConcreteCompany("昆明分公司"); cp1.Add(new HRDepartment("昆明分公司人力资源部")); cp1.Add(new FinanceDepartment("昆明分公司财务部")); root.Add(cp1); ConcreteCompany cp2 = new ConcreteCompany("云大办事处"); cp2.Add(new HRDepartment("云大办事处人力资源部")); cp2.Add(new FinanceDepartment("云大办事处财务部")); cp1.Add(cp2); ConcreteCompany cp3 = new ConcreteCompany("昆工办事处"); cp3.Add(new HRDepartment("昆工办事处人力资源部")); cp3.Add(new FinanceDepartment("昆工办事处财务部")); cp1.Add(cp3); System.out.println("结构图:"); root.Display(1); System.out.println("职责:"); root.LineofDuty();
运行结果:
2-应用场景简单总结
1、当体现部分与整体层次的结构时;
2、希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中所有对象时;