溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時(shí)間:2020-10-03 19:05:09 來(lái)源:腳本之家 閱讀:119 作者:blueberry_mu 欄目:編程語(yǔ)言

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

一、意圖

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

二、適用性

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

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

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

Java 中組合模型之對(duì)象結(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 {
  /**
   * 存儲(chǔ)節(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)造一個(gè)根節(jié)點(diǎn)
    Composite root = new Composite("Root");

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

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

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

    root.addChild(branch2);
    root.addChild(branch3);

    root.doSomething();
  }
}

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

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

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI