标签:
组合模式
一、作用
需求是体现部分与整体的关系时,完成的功能就是基础的对象可以组成成更加复杂的对象,而这个组合的对象又可以进一步的组合,不断的迭代,便可以体现出层次的结构
二、类图(核心在于有一个之类有一个向上的引用)
三、实现
(1)Company定义结构
public abstract class Company { protected String name; public Company(String name) { this.name = name; } public Company(){} public abstract void add(Company company); public abstract void remove(Company company); public abstract void display(); }
(2)具体Company实现类
public class HRCompany extends Company { public HRCompany(String name) { this.name = name; } @Override public void add(Company company) { } @Override public void remove(Company company) { } @Override public void display() { System.out.println(name); } } public class BeiJCompany extends Company { private List<Company> list = new ArrayList<Company>(); public BeiJCompany(String name) { this.name = name; } @Override public void add(Company company) { list.add(company); } @Override public void remove(Company company) { list.remove(company); } @Override public void display() { System.out.println(name); for(Company company: list) { System.out.print("\t"); company.display(); } } }
(3)Client测试类
public class Client { public static void main(String[] args) { Company root = new HRCompany("总部HR"); Company beijingHr = new HRCompany("北京总部HR"); Company beijing = new BeiJCompany("北京分部"); beijing.add(beijingHr); root.display(); beijing.display(); } }
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4384106.html