1. 程式人生 > >設計模式之組合實體模式

設計模式之組合實體模式

一.組合實體模式

定義:物件的組成類似於樹型結構,組成了"部分-整體"的結構,組成的最小單元有相似性,在更高層次的抽象上。

結構:

1.Component(抽象元件),為葉子節點和樹節點提供統一的抽象。

2.Composite(容器構建),在組合物件中表示節點物件,在葉子節點之外的都是該型別的結點。

3.Leaf(葉子構件),在組合物件中表示葉子節點。

類圖為:

 

 Component類

import java.util.ArrayList;

public abstract class Component {
    public  abstract void Opertion(); //操作
    public  abstract void Add(Component Child);//新增子節點
    public  abstract void Remove(int index);//刪除節點
    public  abstract ArrayList<Component> getChild(int index);//獲取子節點
}

Leaf類

import java.util.ArrayList;

public class Leaf extends Component {

    private String leafName =null;

    public Leaf(String leafName) {
        this.leafName = leafName;
    }

    @Override
    public void Opertion() {
        System.out.println(leafName+"正在迎風搖擺");
    }

    @Override
    public void Add(Component Child) {

    }

    @Override
    public void Remove(int index) {

    }

    @Override
    public ArrayList<Component> getChild(int index) {
        return null;
    }

    public String getLeafName() {
        return leafName;
    }

    public void setLeafName(String leafName) {
        this.leafName = leafName;
    }
}

Composite類---->Trunk

import java.util.ArrayList;

public class Trunk extends  Component {

    private String TrunkName;

    private ArrayList<Component> components =new ArrayList<>(); //多個子節點

    public Trunk(String TrunkName) {
        this.TrunkName = TrunkName;
    }

    @Override
    public void Opertion() {
        System.out.println(TrunkName+"樹幹正在抵禦秋風");
        for (Component component: components) {
            component.Opertion();
        }
    }

    @Override
    public void Add(Component Child) {
        components.add(Child);
    }

    @Override
    public void Remove(int index) {
        components.remove(index);
    }

    @Override
    public ArrayList<Component>  getChild(int index) {
        return components;
    }

    public String getTrunkName() {
        return TrunkName;
    }
}

最後執行Main

public class Main {

    public static void main(String[] args) {
        Trunk root = new Trunk("樹根");

        Trunk trunk = new Trunk("主幹");

        Trunk t1 = new Trunk("第一分支");
        Trunk t2 = new Trunk("主分支");
        Trunk t3 = new Trunk("第二分支");

        Leaf l1 = new Leaf("分葉1");
        Leaf l2 = new Leaf("分葉2");
        Leaf l3 = new Leaf("分葉3");
        Leaf l4 = new Leaf("分葉4");
        Leaf l5 = new Leaf("分葉5");

        root.Add(t2);

        t2.Add(t1);
        t2.Add(t3);

        t1.Add(l1);
        t1.Add(l3);
        t1.Add(l5);

        t3.Add(l2);
        t3.Add(l4);

        root.Opertion();
    }
}

總結:類似於樹型結構,使其部分與整體具有結構上的一致性。

優點:結構簡便,使其內部結構透明,對於使用者公開

缺點:根節點部分函式未使用。

&n