最新国产好看的视频,伊人天堂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)文章

最新評論

宜州市| 柞水县| 炉霍县| 清新县| 南召县| 井冈山市| 拜城县| 靖安县| 蕉岭县| 武夷山市| 宁化县| 凤翔县| 密山市| 含山县| 信宜市| 论坛| 志丹县| 南木林县| 唐河县| 连南| 唐山市| 华亭县| 滨海县| 高台县| 六枝特区| 本溪| 马尔康县| 泉州市| 庄河市| 曲靖市| 宿迁市| 阳曲县| 灵台县| 溆浦县| 东港市| 缙云县| 甘洛县| 汉川市| 株洲市| 商南县| 金沙县|