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

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();
    }
}

运行结果

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务