这篇文章主要介绍了java 中组合模型之对象结构模式的详解的相关资料,希望通过本文能帮助到大家理解应用对象结构模型,需要的朋友可以参考下
java 中组合模型之对象结构模式的详解
一、意图
将对象组合成树形结构以表示”部分-整体”的层次结构。composite使得用户对单个对象和组合对象的使用具有一致性。
二、适用性
你想表示对象的部分-整体层次结构
你希望用户忽略组合对象与单个对象的不同,用户将统一使用组合结构中的所有对象。
三、结构
四、代码
public abstract class component {
  protected string name; //节点名
  public component(string name){
    this.name = name;
  }
  public abstract void dosomething();
}
public class composite extends component {
  /**
   * 存储节点的容器
   */
  private list<component> components = new arraylist<>();
  public composite(string name) {
    super(name);
  }
  @override
  public void dosomething() {
    system.out.println(name);
    if(null!=components){
      for(component c: components){
        c.dosomething();
      }
    }
  }
  public void addchild(component child){
    components.add(child);
  }
  public void removechild(component child){
    components.remove(child);
  }
  public component getchildren(int index){
    return components.get(index);
  }
}
public class leaf extends component {
  public leaf(string name) {
    super(name);
  }
  @override
  public void dosomething() {
    system.out.println(name);
  }
}
public class client {
  public static void main(string[] args){
    // 构造一个根节点
    composite root = new composite("root");
    // 构造两个枝干节点
    composite branch1 = new composite("branch1");
    composite branch2 = new composite("branch2");
    // 构造两个叶子节点
    leaf leaf1 = new leaf("leaf1");
    leaf leaf2 = new leaf("leaf2");
    branch1.addchild(leaf1);
    branch2.addchild(leaf2);
    root.addchild(branch1);
    root.addchild(branch2);
    root.dosomething();
  }
}
输出结果:
root
branch1
leaf1
branch2
leaf2
以上就是java中组合模型之对象结构模式的实例分析的详细内容。
   
 
   