Java設計模式筆記之組合模式

1.前言

整體與部分可以被一致對待的問題。組合模式也叫整體與部分模式,是結構性設計模式之一,組合模式比較簡單。它將一組相似的對象看作一個對象處理,並根據一個樹狀結構來組合對象,然後提供一個統一的方法去訪問相應的對象,以此忽略掉對象與對象集合之間的差別。

2.定義

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

3.UML圖


4.應用場景

表示對象的部分-整體層次結構時;從一個整體中能夠獨立出部分模塊或功能的場景。

5.通用模式代碼

//抽象根節點
public abstract class Component {
    //節點名
    protected String name;

    public Component(String name){
        this.name = name;
    }

    /**
     * 具體的邏輯方法由子類去實現
     */
    public abstract void doSomething();

}

//具體枝幹節點
public class Composite extends Component {
    //存儲節點的容器
    private List<Component> componentList = new ArrayList<>();

    /**
     *
     * @param name
     */
    public Composite(String name) {
        super(name);
    }

    @Override
    public void doSomething() {
        Log.d("zsf", "name:" + name);
        if (null != componentList){
            for(Component c :componentList){
                c.doSomething();
            }
        }
    }

    /**
     * 添加子節點
     * @param child 子節點
     */
    public void addChild(Component child){
        componentList.add(child);
    }

    /**
     * 移除子節點
     * @param child 子節點
     */
    public void removeChild(Component child){
        componentList.remove(child);
    }

    /**
     * 獲取子節點
     * @param index 子節點對應的下標
     * @return 子節點
     */
    public Component getChildren(int index){
        return componentList.get(index);
    }

}


//具體葉子節點
public class Leaf extends Component {
 public Leaf(String name) { super(name); } 
 @Override 
 public void doSomething() { 
		Log.d("zsf","name:" + name); 
	}
 }

public class ClientActivity extends Activity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //activity_component_client沒有其他東西
        setContentView(R.layout.activity_component_client);

        //構造一個根節點
        Composite root = new Composite("root");

        //構造兩個枝幹節點
        Composite branch1 = new Composite("branch1");
        Composite branch2 = new Composite("branch2");

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

        //將葉子節點添加到枝幹節點中
        branch1.addChild(leaf1);
        branch2.addChild(leaf2);

        //將枝幹節點添加到根節點中
        root.addChild(branch1);
        root.addChild(branch2);

        //執行方法
        root.doSomething();


    }
}

將Composite中的方法同樣定義到了Component中去。將組合所使用的方法定義在抽象類的方式稱爲透明的組合模式。上一個組合模式叫安全的組合模式。透明組合模式的UML圖如下:







發佈了105 篇原創文章 · 獲贊 35 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章