大话设计模式_组合模式
以总公司下设分公司用一套系统为例子.
package com.wzs.design;import java.util.ArrayList;import java.util.List;/** * 大话设计模式--page194 组合模式 * * @author Administrator * */public class CompositeMode {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();}}// 公司抽象类abstract class Company {public String name;public Company(String name) {this.name = name;}public abstract void add(Company company);// 增加public abstract void remove(Company company);// 移除public abstract void display(int depth);// 显示public abstract void lineOfDuty();// 履行职责}// 具体公司类class ConcreteCompany extends Company {private List<Company> children = new ArrayList<Company>();public ConcreteCompany(String name) {super(name);}@Overridepublic void add(Company company) {children.add(company);}@Overridepublic void display(int depth) {System.out.println(MyString.createString("-", depth) + " " + this.name);for (Company company : children) {company.display(depth + 2);}}@Overridepublic void lineOfDuty() {for (Company company : children) {company.lineOfDuty();}}@Overridepublic void remove(Company company) {children.remove(company);}}// 人力资源部class HRDepartment extends Company {public HRDepartment(String name) {super(name);}@Overridepublic void add(Company company) {}@Overridepublic void display(int depth) {System.out.println(MyString.createString("-", depth) + " " + this.name);}@Overridepublic void lineOfDuty() {System.out.println(this.name + " 员工招聘培训管理.");}@Overridepublic void remove(Company company) {}}// 财务部class FinanceDepartment extends Company {public FinanceDepartment(String name) {super(name);}@Overridepublic void add(Company company) {}@Overridepublic void display(int depth) {System.out.println(MyString.createString("-", depth) + " " + this.name);}@Overridepublic void lineOfDuty() {System.out.println(this.name + " 公司财务收支管理.");}@Overridepublic void remove(Company company) {}}/* * 创造字符前缀 */class MyString {public static String createString(String str, int depth) {String strTemp = "";for (int i = 0; i < depth; i++) {strTemp += str;}return strTemp;}}