码迷,mamicode.com
首页 > 其他好文 > 详细

组合模式(Composite Pattern)

时间:2016-05-24 13:22:53      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

组合模式:把一组相似的对象当成一个单一的对象,依据树形结构来组合对象,用来表示部分和整体层次。

 

举一个管理公司员工的例子:

public class Employee {
    private String name;
    private String dept;
    private double salary;
    private List<Employee> sub;

    public Employee(String n,String d,int s) {
        name = n;
        dept = d;
        salary = s;
        sub = new ArrayList<Employee>();  
    }
    public void add(Employee e) {
        sub.add(e);
    }
    public void remove(Emplyee e) {
        sub.remove(e);
    }
public List<Employee> getSub() {
    return sub;
  }
public String toString() {
        return "Name:" + name + "dept:" + depr + "salary:" + salary;
   }
}

 

测试代码:

Employee CEO = new Employee("A0","CEO",30000);

Employee headMarketing = new Employee("B0","Head Marketing", 20000);
Employee clerk1 = new Employee("C0","Marketing",10000);
Employee clerk2 = new Employee("C1","Marketing",10000);


Employee headSales = new Employee("B1","Head Sales",20000);
Employee sale1 = new Employee("C2","Marketing",10000);
Employee sale2 = new Employee("C3","Marketing",10000);

CEO.add(headMarking);    //CEO管理headMarking
CEO.add(headSales);       // CEO管理headSales

headMarking.add(clerk1);   //headMarking管理两个人
headMarking.add(clerk2);

headSales.add(sale1);    //headSales管理两个人
headSales.add(sale2);

//打印所有员工
System.out.println(CEO);
for(Employee e1 : CEO.getSub()) {
    System.out.println(e1);
    for(Employee e2: e1.getSub()) {
        System.out.println(e2);
    }
}

 组合模式适合处理树形结构问题,如树形菜单,文件夹文件管理。

组合模式(Composite Pattern)

标签:

原文地址:http://www.cnblogs.com/13jhzeng/p/5522931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!