Java组合模式

x33g5p2x  于10个月前 转载在 Java  
字(2.1k)|赞(0)|评价(0)|浏览(67)

Java组合模式

说是组合模式 其实就是 树节点 ,如果学过xml文件document文档操作的话 那么 这个模式就很好理解了

使用场景: 树形菜单,文件、文件夹的管理。

我们来演示一个案例 公司层级关系

public class Employee {
    private String name;  //名称
    private String dept;  //职位
    private int salary;  //薪水
    private List<Employee> subordinates;//子集合Employee

    //构造函数
    public Employee(String name,String dept, int sal) {
        this.name = name;
        this.dept = dept;
        this.salary = sal;
        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","销售经理", 20000);
                    Employee salesExecutive1 = new Employee("Richard","销售", 10000);
                    Employee salesExecutive2 = new Employee("Rob","销售", 10000);

            Employee headMarketing = new Employee("Michel","营销经理", 20000);
                    Employee clerk1 = new Employee("Laura","营销", 10000);
                    Employee clerk2 = new Employee("Bob","营销", 10000);

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

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

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

        //打印该组织的所有员工
        System.out.println("根节点:"+CEO);
        for (Employee headEmployee : CEO.getSubordinates()) {
            System.out.println("\t"+headEmployee);
            for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println("\t\t"+employee);
            }
        }
    }
}

根节点:Employee :[ Name : John, dept : CEO, salary :30000 ]
Employee :[ Name : Robert, dept : 销售经理, salary :20000 ]
Employee :[ Name : Richard, dept : 销售, salary :10000 ]
Employee :[ Name : Rob, dept : 销售, salary :10000 ]
Employee :[ Name : Michel, dept : 营销经理, salary :20000 ]
Employee :[ Name : Laura, dept : 营销, salary :10000 ]
Employee :[ Name : Bob, dept : 营销, salary :10000 ]

从结果中我们可以看出来

CEO是根节点 根节点下的子节点就是经理 经理下的子节点就是员工
点赞 -收藏-关注-便于以后复习和收到最新内容有其他问题在评论区讨论-或者私信我-收到会在第一时间回复如有侵权,请私信联系我感谢,配合,希望我的努力对你有帮助^_^

相关文章

热门文章

更多