大话设计模式-组合模式的实践-公司部门

UML

公司抽象类

/** * 公司抽象类 */
public abstract class Company {
    protected 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);

    protected String getDepth(int depth) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            stringBuilder.append('-');
        }
        return stringBuilder.toString();
    }

    /** * 各部门履行职责 */
    public abstract void invoke();
}

具体公司

import java.util.ArrayList;
import java.util.List;

public class ConcreteCompany extends Company {
    private List<Company> companies = new ArrayList<>();

    public ConcreteCompany(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) {
        System.out.println(getDepth(depth) + name);
        for (Company company : companies) {
            company.display(depth + 2);
        }
    }

    @Override
    public void invoke() {
        for (Company company : companies) {
            company.invoke();
        }
    }
}

两个部门

public class HRDepartment extends Company {
    public HRDepartment(String name) {
        super(name);
    }

    @Override
    public void add(Company company) {

    }

    @Override
    public void remove(Company company) {

    }

    @Override
    public void display(int depth) {
        System.out.println(getDepth(depth) + name);
    }

    @Override
    public void invoke() {
        System.out.println(name + " 履行HR部门的职责");
    }
}

public class FinanceDepartment extends Company {
    public FinanceDepartment(String name) {
        super(name);
    }

    @Override
    public void add(Company company) {

    }

    @Override
    public void remove(Company company) {

    }

    @Override
    public void display(int depth) {
        System.out.println(getDepth(depth) + name);
    }

    @Override
    public void invoke() {
        System.out.println(name +" 履行财务部门的职责");
    }
}

测试类

public class Main {
    public static void main(String[] args) {
        ConcreteCompany root = new ConcreteCompany("北京百度总公司");
        root.add(new HRDepartment("北京人力资源部"));
        root.add(new FinanceDepartment("北京财务部"));

        ConcreteCompany concreteCompany = new ConcreteCompany("山东济南分公司");
        concreteCompany.add(new HRDepartment("济南人力资源部"));
        concreteCompany.add(new FinanceDepartment("济南财务部"));

        root.add(concreteCompany);
        root.display(1);
        root.invoke();
    }
}

运行结果

全部评论

相关推荐

点赞 评论 收藏
分享
整顿职场的柯基很威猛:这种不可怕,最可怕的是夹在一帮名校里的二本选手,人家才是最稳的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务