標籤:設計模式 合成模式
原文地址:http://leihuang.org/2014/12/09/composite/
Structural 模式 如何設計物件之間的靜態結構,如何完成物件之間的繼承、實 現與依賴關係,這關乎著系統設計出來是否健壯(robust):像是易懂、易維護、易修改、耦合度低等等議題。Structural 模式正如其名,其分類下的模式給出了在不同場合下所適用的各種物件關係結構。
- Default Adapter 模式
- Adapter 模式
- Bridge 模式
- Composite 模式
- Decorator 模式
- Facade 模式
- Flyweight 模式
- Proxy 模式
Composite模式是構造型的設計模式之一,通過遞迴手段來構造諸如檔案系統之類的樹形的對象結構;Composite模式所代表的資料構造是一群具有統一介面介面的對象集合,並可以通過一個對象來訪問所有的對象(遍曆)。
舉個例子,比如一棵樹包括樹枝和樹葉,樹枝上面又有樹枝和樹葉,這樣一直迴圈下去...如
假如讓你實現一棵樹,你會不會把每一個樹枝都給定義出來?肯定不會.那麼這就需要用到組合模式.組合模式基本結構如.
我們現在就利用組合模式來實現,這棵樹.
IBranch 介面
public interface IBranch { public void print() ;}
Leaf 類
public class Leaf implements IBranch { private String leaf = null ; public Leaf(String leaf){ this.leaf = leaf ; } @Override public void print() { System.out.println(leaf); }}
BranchComposite 類
import java.util.LinkedList;import java.util.List;public class BranchComposite implements IBranch { private List<IBranch> branchList = null ; public BranchComposite(){ branchList = new LinkedList<IBranch>() ; } public void add(IBranch branch){ branchList.add(branch) ; } public boolean remove(IBranch branch){ return branchList.remove(branch) ; } @Override public void print() { for(IBranch branch : branchList){ branch.print(); } }}
Client 類
public class Client { public static void main(String[] args) { IBranch leaf1 = new Leaf("leaf 1") ; IBranch leaf2 = new Leaf("leaf 2") ; IBranch leaf3 = new Leaf("leaf 3") ; BranchComposite branch0 = new BranchComposite() ; BranchComposite branch1 = new BranchComposite() ; BranchComposite branch2 = new BranchComposite() ; branch0.add(leaf1); branch0.add(branch1); branch1.add(leaf2); branch1.add(branch2); branch2.add(leaf3); //branch0.print() ; //branch1.print() ; //branch2.print() ; }}
2014-12-09 17:09:18
Brave,Happy,Thanksgiving !
設計模式:合成模式