组合模式代码举例(java语言版)

前言:将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。使用场景:部分、整体场景,如树形菜单,文件、文件夹的管理。

JAVA语言版组合模式

创建实体类:

public class Employee {
    private String name;
    private String position;
    private int salary;
    private List subordinates;

    public Employee(String name, String position, int salary) {
        this.name = name;
        this.position = position;
        this.salary = salary;
        this.subordinates = new ArrayList<>();
    }

    public void add(Employee employee) {
        subordinates.add(employee);
    }

    public void remove(Employee employee) {
        subordinates.remove(employee);
    }

    public List getSubordinates() {
        return subordinates;
    }

    @Override
    public String toString() {
        return name + " " + position + " " + salary;
    }
}

使用 Employee 类来创建和打印员工的层次结构:

public class CompositePatternDemo {
    public static void main(String[] args) {
        Employee CEO = new Employee("刘海云", "CEO", 30000);
        Employee headSales = new Employee("李国仁", "销售领队", 15000);
        Employee headMarketing = new Employee("张云", "店长", 15000);
        Employee clerkOne = new Employee("小明", "店员", 8000);
        Employee clerkTwo = new Employee("小李", "店员", 8000);
        Employee salesExecutiveOne = new Employee("大状", "销售员", 80000);
        Employee salesExecutiveTwo = new Employee("大雄", "销售员", 80000);

        CEO.add(headSales);
        CEO.add(headMarketing);
        headSales.add(salesExecutiveOne);
        headSales.add(salesExecutiveTwo);
        headMarketing.add(clerkOne);
        headMarketing.add(clerkTwo);

        System.out.println(CEO.toString());
        for (Employee headEmployee : CEO.getSubordinates()) {
            System.out.println(headEmployee.toString());
            for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println(employee.toString());
            }
        }
    }
}

输出结果:

刘海云 CEO 30000
李国仁 销售领队 15000
大状 销售员 80000
大雄 销售员 80000
张云 店长 15000
小明 店员 8000
小李 店员 8000

 

你可能感兴趣的:(设计模式)