八、组合模式
1 应用场景?
表示整体和部分关系时,比如公司分公司以及部门之间的层次结构关系。
2 优点?
实现被组合的对象之间的扩展。比如总公司下可以添加各个分公司,分公司之间是松耦合的,可以方便的扩展出更多的分公司。
3 demo?
package com.biao.combine.again; import java.util.ArrayList; import java.util.List; public class Combine { public static void main(String[] args) { Company company = new ConcreteCompany("bs总公司"); Company company1 = new ConcreteCompany("bs北京分公司"); Company company2 = new ConcreteCompany("bs上海分公司"); FinanceDepartment finance = new FinanceDepartment("bs总财务部"); FinanceDepartment finance2 = new FinanceDepartment("bs上海财务部"); FinanceDepartment finance1 = new FinanceDepartment("bs北京财务部"); company.add(company1); company.add(company2); company.add(finance); finance.add(finance1); finance.add(finance2); company.show(2); // finance.show(4); } } abstract class Company{ public String name; abstract void add(Company company); abstract void remove(Company company); abstract void show(int detpy); } class ConcreteCompany extends Company{ private List<Company> list = new ArrayList<Company>(); public ConcreteCompany(String name) { // TODO Auto-generated constructor stub this.name = name; } @Override void add(Company company) { // TODO Auto-generated method stub list.add(company); } @Override void remove(Company company) { // TODO Auto-generated method stub list.remove(company); } @Override void show(int detpy) { // TODO Auto-generated method stub StringBuilder sb = new StringBuilder(); for(int i=0;i<detpy;i++){ sb.append("-"); } System.out.println(new String(sb)+name); for (Company company : list) { company.show(detpy+2); } } } class HRDepartment extends Company{ List<Company>list = new ArrayList<>(); @Override void add(Company company) { // TODO Auto-generated method stub list.add(company); } @Override void remove(Company company) { // TODO Auto-generated method stub list.remove(company); } @Override void show(int detpy) { // TODO Auto-generated method stub StringBuffer sb = new StringBuffer(); for(int i=0;i<detpy;i++){ sb.append("-"); } System.out.println(new String(sb)+name); for (Company company : list) { company.show(detpy+2); } } } class FinanceDepartment extends Company{ List<Company>list = new ArrayList<>(); public FinanceDepartment(String name) { // TODO Auto-generated constructor stub this.name = name; } @Override void add(Company company) { // TODO Auto-generated method stub list.add(company); } @Override void remove(Company company) { // TODO Auto-generated method stub list.remove(company); } @Override void show(int detpy) { // TODO Auto-generated method stub StringBuffer sb = new StringBuffer(); for(int i=0;i<detpy;i++){ sb.append("-"); } System.out.println(new String(sb)+name); for (Company company : list) { company.show(detpy+2); } } }