JAVA 設計模式 組合模式


用途


組合模式 (Component)
將對象組合成 樹形結構以表示“部分-整體”的層次結構。
組合模式使得用戶對單個對象和組合對象的使用具有 唯一性
組合模式是一種 結構型模式


結構
圖-組合模式結構圖

Component : 組合中的對象聲明接口,在適當的情況下,實現所有類共有接口的默認行為。聲明一個接口用於訪問和管理 Component 的子部件。

abstract  class Component {
     protected String name;
    
     public Component(String name) {
         this.name = name;
    }
    
     public  abstract  void Add(Component c);
     public  abstract  void Remove(Component c);
     public  abstract  void Display( int depth);
}

Leaf : 表示葉節點對象。葉子節點沒有子節點。

class Leaf  extends Component {

     public Leaf(String name) {
         super(name);
    }

    @Override
     public  void Add(Component c) {
        System.out.println("Can not add to a leaf");
    }

    @Override
     public  void Remove(Component c) {
        System.out.println("Can not remove from a leaf");
    }

    @Override
     public  void Display( int depth) {
        String temp = "";
         for ( int i = 0; i < depth; i++) 
            temp += '-';
        System.out.println(temp + name);
    }
    
}

Composite : 定義枝節點行為,用來存儲子部件,在 Component 接口中實現與子部件相關的操作。例如 Add 和 Remove。

class Composite  extends Component {

     private List<Component> children =  new ArrayList<Component>();
    
     public Composite(String name) {
         super(name);
    }

    @Override
     public  void Add(Component c) {
        children.add(c);
    }

    @Override
     public  void Remove(Component c) {
        children.remove(c);
    }

    @Override
     public  void Display( int depth) {
        String temp = "";
         for ( int i = 0; i < depth; i++) 
            temp += '-';
        System.out.println(temp + name);
        
         for (Component c : children) {
            c.Display(depth + 2);
        }
    }
    
}

Client : 通過 Component 接口操作結構中的對象。

public  class CompositePattern {

     public  static  void main(String[] args) {
        Composite root =  new Composite("root");
        root.Add( new Leaf("Leaf A"));
        root.Add( new Leaf("Leaf B"));
        
        Composite compX =  new Composite("Composite X");
        compX.Add( new Leaf("Leaf XA"));
        compX.Add( new Leaf("Leaf XB"));
        root.Add(compX);
        
        Composite compXY =  new Composite("Composite XY");
        compXY.Add( new Leaf("Leaf XYA"));
        compXY.Add( new Leaf("Leaf XYB"));
        compX.Add(compXY);
        
        root.Display(1);
    }

}



應用場景
1、想要表示對象的部分-整體層次結構。

2、想要客戶端忽略組合對象與單個對象的差異,客戶端將統一地使用組合結構中的所有對象。

關於分級數據結構的一個普遍性的例子是你每次使用電腦時所遇到的: 文件系統

文件系統由目錄和文件組成。每個目錄都可以裝內容。目錄的內容可以是文件,也 可以是目錄。

按照這種方式,計算機的文件系統就是以遞歸結構來組織的。如果你想要描述這樣的數據結構,那么你可以使用組合模式。


 

要點


組合模式定義由 Leaf 對象和 Composite 對象組成的類結構;

它使得客戶端變得簡單;

它使得添加或刪除子部件變得很容易。



推薦

本文屬於 JAVA設計模式系列



參考資料

《大話設計模式》

《HeadFirst設計模式》

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM