组合模式(Composite Pattern)

   

      像一个树形结构一样使用基本的对象和自己本身构建一个复杂的对象,称为组合模式。 这种模式很容易学习以及应用到某个系统中。组合模式属于结构设计模式之一,比较常用。经典的UML图如下:

组合模式(Composite Pattern)_第1张图片

       一个简单的实例程序来说明组合模式是如何实现的。定义一个Employee类,充当组合模式中的表演者,CompositePatternDemo作为测试类。

public class Employee {
    private String name;
    private String dept;
    private int salary;
    private List<Employee> subordinates;

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

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

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

    public List<Employee> getSubordinates(){
        return subordinates;
    }

    public String toString(){
        return ("Employee :[ Name : "+ name
                +", dept : "+ dept + ", salary :"
                + salary+" ]");
    }

}

    测试代码:

public class CompositePatternDemo {
    public static void main(String[] args) {
        Employee CEO = new Employee("John","CEO", 30000);

        Employee headSales = new Employee("Robert","Head Sales", 20000);

        Employee headMarketing = new Employee("Michel","Head Marketing", 20000);

        Employee clerk1 = new Employee("Laura","Marketing", 10000);
        Employee clerk2 = new Employee("Bob","Marketing", 10000);

        Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
        Employee salesExecutive2 = new Employee("Rob","Sales", 10000);

        CEO.add(headSales);
        CEO.add(headMarketing);

        headSales.add(salesExecutive1);
        headSales.add(salesExecutive2);

        headMarketing.add(clerk1);
        headMarketing.add(clerk2);

        //print all employees of the organization
        System.out.println(CEO);
        for (Employee headEmployee : CEO.getSubordinates()) {
            System.out.println(headEmployee);
            for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println(employee);
            }
        }
    }
}

      测试结果:


Employee :[ Name : John, dept : CEO, salary :0 ]
Employee :[ Name : Robert, dept : Head Sales, salary :0 ]
Employee :[ Name : Richard, dept : Sales, salary :0 ]
Employee :[ Name : Rob, dept : Sales, salary :0 ]
Employee :[ Name : Michel, dept : Head Marketing, salary :0 ]
Employee :[ Name : Laura, dept : Marketing, salary :0 ]
Employee :[ Name : Bob, dept : Marketing, salary :0 ]

        

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