组合模式

public abstract class Component {
2
3 protected String name;
4
5 public Component(String name) {
6 this.name = name;
7 }
8
9 //获取分支下的所有叶子构件和树枝构件
10 public abstract void display(int depth);
11
12 }

public class Composite extends Component {
2
3 public Composite(String name) {
4 super(name);
5 }
6
7 //构建容器
8 private ArrayList componentArrayList = new ArrayList();
9
10 //增加一个叶子构件或树枝构件
11 public void add(Component component) {
12 this.componentArrayList.add(component);
13 }
14
15 //删除一个叶子构件或树枝构件
16 public void remove(Component component) {
17 this.componentArrayList.remove(component);
18 }
19
20 @Override
21 public void display(int depth) {
22 //输出树形结构
23 for(int i=0; i<depth; i++) {
24 System.out.print(’-’);
25 }
26 System.out.println(name);
27
28 //下级遍历
29 for (Component component : componentArrayList) {
30 component.display(depth + 1);
31 }
32 }
33
34 }

public class Leaf extends Component {
2
3 public Leaf(String name) {
4 super(name);
5 }
6
7 @Override
8 public void display(int depth) {
9 //输出树形结构的叶子节点
10 for(int i=0; i<depth; i++) {
11 System.out.print(’-’);
12 }
13 System.out.println(name);
14 }
15
16 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值