成人午夜视频全免费观看高清-秋霞福利视频一区二区三区-国产精品久久久久电影小说-亚洲不卡区三一区三区一区

Java中組合模型之對象結構模式的詳解

Java 中組合模型之對象結構模式的詳解

成都創(chuàng)新互聯(lián)公司成立于2013年,先為彰武等服務建站,彰武等地企業(yè),進行企業(yè)商務咨詢服務。為彰武企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務解決您的所有建站問題。

一、意圖

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

二、適用性

你想表示對象的部分-整體層次結構

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

三、結構

Java 中組合模型之對象結構模式的詳解

四、代碼

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

  public abstract void doSomething();
}

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

    // 構造兩個枝干節(jié)點
    Composite branch2 = new Composite("Branch2");
    Composite branch3 = new Composite("Branch3");

    // 構造兩個葉子節(jié)點
    Leaf leaf1 = new Leaf("Leaf1");
    Leaf leaf2 = new Leaf("Leaf2");

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

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

    root.doSomething();
  }
}

輸出結果:
Root
Branch2
Leaf1
Branch3
Leaf2

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

網(wǎng)站名稱:Java中組合模型之對象結構模式的詳解
文章轉載:http://jinyejixie.com/article28/ggchcp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供小程序開發(fā)、手機網(wǎng)站建設網(wǎng)站排名、ChatGPT、電子商務、自適應網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設