设计模式(15)-组合模式

定义
通过树型结构建立对象间的父子关系.

实例
员工间的管理关系,ceo管理销售经理和财务经理,每个经理又管理着普通员工.

1.抽象员工类

public abstract class Corp {
    private String name="";
    private String position="";

    //构造函数
    public Corp(String name,String position){
        this.name = name;
        this.position = position;
    }

    //父节点属性及getset方法
    private Corp parent = null;

    public Corp getParent(){
        return this.parent;
    }

    public void setParent(Corp parent){
        this.parent = parent;
    }

    //获取子节点
    public abstract ArrayList<Corp> getChildList();

    //增加子节点
    public abstract void addChild(Corp corp);

    public String getInfo(){
        StringBuffer info = new StringBuffer();
        info.append("姓名:"+this.name+",职位:"+position);
        return info.toString();
    }
}

2.分支节点类
一般根节点也是一种分支,所以此处为求简便不单独定义Root.

public class Branch extends Corp{
    //构造函数
    public Branch(String name, String position) {
        super(name, position);
    }

    private ArrayList<Corp> childList = new ArrayList<Corp>();

    //获取子节点列表
    public ArrayList<Corp> getChildList(){
        return this.childList;
    }

    //增加子节点
    public void addChild(Corp corp){
        corp.setParent(this);
        this.childList.add(corp);
    }
}

3.叶子节点

public class Leaf extends Corp{
    //构造函数
    public Leaf(String name, String position) {
        super(name, position);
    }

    //空实现,抛出操作异常
    @Override
    public ArrayList<Corp> getChildList() throws UnsupportedOperationException{
        throw new UnsupportedOperationException();
    }

    //空实现,抛出操作异常
    @Override
    public void addChild(Corp corp) throws UnsupportedOperationException{
        throw new UnsupportedOperationException();
    }
}

4.运行

public class Client {
    public static void main(String[] args) {
        Corp ceo = new Branch("张三", "总经理");
        Corp saleManager = new Branch("李四","销售经理");
        Corp financeManager = new Branch("王五", "财务经理");
        Corp sale1 = new Leaf("李四一","销售人员");
        Corp sale2 = new Leaf("李四二","销售人员");
        Corp finance1 = new Leaf("王五一","财务人员");
        Corp finance2 = new Leaf("王五二","财务人员");

        //建立关系
        saleManager.addChild(sale1);
        saleManager.addChild(sale2);

        financeManager.addChild(finance1);
        financeManager.addChild(finance2);

        ceo.addChild(saleManager);
        ceo.addChild(financeManager);

        //遍历
        display(ceo);

    }

    //遍历
    public static void display(Corp corp){
        System.out.println(corp.getInfo());
        for(Corp c:corp.getChildList()){
            if(c instanceof Branch){
                display(c);
            }else{
                System.out.println(c.getInfo());
            }
        }
    }
}

结果:

姓名:张三,职位:总经理
姓名:李四,职位:销售经理
姓名:李四一,职位:销售人员
姓名:李四二,职位:销售人员
姓名:王五,职位:财务经理
姓名:王五一,职位:财务人员
姓名:王五二,职位:财务人员

猜你喜欢

转载自blog.csdn.net/chixiaoen/article/details/79422396
今日推荐