赞
踩
又称部分整体模式,将对象组合成树形结构以表示‘部分-整体’的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性
UML图:
应用场景
总公司、分公司、部门关系
public abstract class Company { protected String name; public Company(String name) { this.name = name; } /** * 添加公司 * * @param company */ public abstract void add(Company company); /** * 删除公司 * * @param company */ public abstract void remove(Company company); /** * 展示公司 * * @param depth */ public abstract void display(int depth); }
public class ConcretCompany extends Company { List<Company> companies = new ArrayList<>(); public ConcretCompany(String name) { super(name); } @Override public void add(Company company) { companies.add(company); } @Override public void remove(Company company) { companies.remove(company); } @Override public void display(int depth) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; i++) { sb.append("-"); } System.out.println(sb + this.name); for (Company company : companies) { // 分级 company.display(depth + 2); } } }
public class Department extends Company { public Department(String name) { super(name); } @Override public void add(Company company) { } @Override public void remove(Company company) { } @Override public void display(int depth) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; i++) { sb.append("-"); } System.out.println(sb + this.name); } }
public class Main { public static void main(String[] args) { Company company = new ConcretCompany("总公司"); Company department01 = new Department("人事部门"); Company department02 = new Department("数字部门"); company.add(department01); company.add(department02); Company company1 = new ConcretCompany("分公司01"); Company department03 = new Department("分公司01的数字部门"); company1.add(department03); Company company2 = new ConcretCompany("分公司02"); Company department04 = new Department("分公司02的数字部门"); company2.add(department04); company.add(company1); company.add(company2); // 总公司架构 company.display(0); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。