设计模式(组合模式)

组合模式是为了解决业务中“局部-整体”的关系,这里的局部整体互相嵌套,且具备相同的处理接口。

典型的角色是两个:

  • component:包含自身抽象列表的类,下例中为Employee;
  • composite:各个组成部分对外暴露的处理接口,下例中为toString,为单独抽象;

代码如下:

  • Employee
package com.example;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Employee {

    private String name;
    private String deptname;
    private List<Employee> subs;
    
    public Employee(String name, String deptname){
        this.name = name;
        this.deptname = deptname;
        subs = new ArrayList<Employee>();        
    }

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

    public void remove(Employee e) {
        for (Iterator<Employee> it = subs.iterator(); it.hasNext();) {
            if (((Employee) it.next()).name == e.name) {
                it.remove();
            }
        }
    }
    
    //这里的toString,等价于于composite方法
    public String toString() {
        return ("Employee :[ Name : " + name + ", dept : " + deptname + " ]");
    }

    public List<Employee> getSubs() {
        return subs;
    }

}
  • App 测试类
public class App {

    public static void main(String[] args) {
        Employee e1 = new Employee("fredric", "dept1");
        Employee e2 = new Employee("sinny", "dept2");
        Employee e3 = new Employee("baobao", "dept2");
        e1.add(e2);
        e1.add(e3);
        for(Employee emp:e1.getSubs()){
            System.out.println(emp);
        }
        e1.remove(e2);
        for(Employee emp:e1.getSubs()){
            System.out.println(emp);
        }        
    }
}
posted @ 2015-06-12 16:27  Fredric_2013  阅读(212)  评论(0编辑  收藏  举报