组合模式Composite

 

    组合模式(Composite):将对象组合成树形结构以表示“部分--整体”的层次结构。

组合模式使得用户对单个对象和组合对象的使用具有一致性

 

    下面是类结构图:

    下面是源代码:

    Component.java

 

package com.china_chenglong;

public abstract class Component {

protected String name;

public Component(String name){

this.name = name;

}

public abstract void Add(Component c);

public abstract void Remove(Component c);

public abstract void Display(int dept);

}

    Leaf.java
package com.china_chenglong;
public class Leaf extends Component {
public Leaf(String name){
super(name);
}
public void Add(Component c) {
}
public void Display(int dept) {
String str = "";
for(int i=0;i<dept;i++){
str+="-";
}
System.out.println(str+this.name);
}
public void Remove(Component c) {
}
}
    Main.java
package com.china_chenglong;
public class Main {
public static void main(String[] args) {
Composite root = new Composite("root");
Composite root2 = new Composite("root2");
Leaf leafA = new Leaf("LeafA");
Leaf leafB = new Leaf("LeafB");
root2.Add(leafA);
root2.Add(leafB);
Composite root3 = new Composite("root3");
Leaf leafC = new Leaf("LeafC");
Leaf leafD = new Leaf("LeafD");
root3.Add(leafC);
root3.Add(leafD);
root.Add(root2);
root.Add(root3);
root.Display(1);
}
}

 

 

   Composite.java

package com.china_chenglong;

import java.util.*;

public class Composite extends Component {

 

private List<Component> list = new ArrayList<Component>();

public Composite(String name){

super(name);

}

public void Add(Component c) {

list.add(c);

}

 

public void Display(int dept) {

String str = "";

for(int i=0;i<dept;i++){

str+="-";

}

System.out.println(str+this.name);

for(int i=0;i<list.size();i++){

list.get(i).Display(dept+2);

}

}

 

public void Remove(Component c) {

list.remove(c);

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值