java composite_关于Java 设计模式 组合模式 Composite

f2023fd608536c136af923ecf8ba2a47.png

1、Tree.java

package com.ssm.cts.pattern.composite;

public abstract class Tree {

// 姓名

private String name = "";

// 职位

private String position = "";

public Tree(String _name, String _position) {

this.name = _name;

this.position = _position;

}

public String getInfo() {

String info = "";

info = "姓名:" + this.name + "\t职位:" + this.position;

return info;

}

}

2、Branch.java

package com.ssm.cts.pattern.composite;

import java.util.ArrayList;

public class Branch extends Tree {

ArrayList subList = new ArrayList();

public Branch(String _name, String _position) {

super(_name, _position);

}

// 增加下属

public void addSub(Tree corp) {

this.subList.add(corp);

}

// 获取下属列表

public ArrayList getSub() {

return this.subList;

}

}

3、Leaf.java

package com.ssm.cts.pattern.composite;

public class Leaf extends Tree {

public Leaf(String _name, String _position) {

super(_name, _position);

}

}

4、Demo.java

package com.ssm.cts.pattern.composite;

import java.util.ArrayList;

public class Demo {

// 测试

public static void main(String[] args) {

// 组装组织架构

Branch ceo = compositeCorpTree();

// 事业部总监

System.out.println(ceo.getInfo());

// 所有员工信息

System.out.println(getTreeInfo(ceo));

}

// 组装树结构

public static Branch compositeCorpTree() {

// 事业部总监

Branch root = new Branch("蒋智昊", "总监");

// 两个部门经理

Branch deptA = new Branch("叶", "规划部总经理");

Branch deptB = new Branch("张", "研发部总经理");

// 组长

Branch groupA = new Branch("赵组长", "规划一组组长");

Branch groupB = new Branch("王组长", "规划二组组长");

// 职员

Leaf a = new Leaf("a", "规划人员");

Leaf b = new Leaf("b", "规划人员");

Leaf c = new Leaf("a", "规划人员");

Leaf d = new Leaf("b", "规划人员");

Leaf h = new Leaf("h", "研发人员");

Leaf i = new Leaf("i", "研发人员");

// 开始组装

root.addSub(deptA);

root.addSub(deptB);

// 部门经理

deptA.addSub(groupA);

deptA.addSub(groupB);

// 规划部职员

groupA.addSub(a);

groupA.addSub(b);

groupB.addSub(c);

groupB.addSub(d);

// 研发部职员

deptB.addSub(h);

deptB.addSub(i);

return root;

}

// 遍历整棵树

public static String getTreeInfo(Branch root) {

ArrayList subList = root.getSub();

String info = "";

for (Tree s : subList) {

if (s instanceof Leaf) {

// 无下属

info = info + s.getInfo() + "\n";

} else {

// 有下属

info = info + s.getInfo() + "\n" + getTreeInfo((Branch) s);

}

}

return info;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值