最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java 中組合模型之對象結(jié)構(gòu)模式的詳解

 更新時間:2017年09月09日 11:23:09   作者:blueberry_mu  
這篇文章主要介紹了Java 中組合模型之對象結(jié)構(gòu)模式的詳解的相關(guān)資料,希望通過本文能幫助到大家理解應(yīng)用對象結(jié)構(gòu)模型,需要的朋友可以參考下

Java 中組合模型之對象結(jié)構(gòu)模式的詳解

一、意圖

將對象組合成樹形結(jié)構(gòu)以表示”部分-整體”的層次結(jié)構(gòu)。Composite使得用戶對單個對象和組合對象的使用具有一致性。

二、適用性

你想表示對象的部分-整體層次結(jié)構(gòu)

你希望用戶忽略組合對象與單個對象的不同,用戶將統(tǒng)一使用組合結(jié)構(gòu)中的所有對象。

三、結(jié)構(gòu)

四、代碼

public abstract class Component {
  protected String name; //節(jié)點(diǎn)名
  public Component(String name){
    this.name = name;
  }

  public abstract void doSomething();
}

public class Composite extends Component {
  /**
   * 存儲節(jié)點(diǎn)的容器
   */
  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){
    // 構(gòu)造一個根節(jié)點(diǎn)
    Composite root = new Composite("Root");

    // 構(gòu)造兩個枝干節(jié)點(diǎn)
    Composite branch1 = new Composite("Branch1");
    Composite branch2 = new Composite("Branch2");

    // 構(gòu)造兩個葉子節(jié)點(diǎn)
    Leaf leaf1 = new Leaf("Leaf1");
    Leaf leaf2 = new Leaf("Leaf2");

    branch1.addChild(leaf1);
    branch2.addChild(leaf2);

    root.addChild(branch1);
    root.addChild(branch2);

    root.doSomething();
  }
}

輸出結(jié)果:
Root
Branch1
Leaf1
Branch2
Leaf2

如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

您可能感興趣的文章:

相關(guān)文章

最新評論

湘潭市| 简阳市| 河津市| 长宁县| 介休市| 安福县| 荆州市| 腾冲县| 改则县| 和硕县| 泸水县| 峨山| 鄯善县| 尤溪县| 南通市| 赣州市| 杨浦区| 张北县| 武功县| 上杭县| 临城县| 罗甸县| 渝中区| 邵阳市| 滨州市| 房产| 易门县| 松溪县| 尉犁县| 巫山县| 绍兴县| 吉隆县| 金山区| 司法| 凌云县| 冀州市| 凤冈县| 寻甸| 淅川县| 贺兰县| 郁南县|