一.組合實體模式java
定義:對象的組成相似於樹型結構,組成了"部分-總體"的結構,組成的最小單元有類似性,在更高層次的抽象上。ide
結構:函數
1.Component(抽象組件),爲葉子節點和樹節點提供統一的抽象。this
2.Composite(容器構建),在組合對象中表示節點對象,在葉子節點以外的都是該類型的結點。spa
3.Leaf(葉子構件),在組合對象中表示葉子節點。code
類圖爲:component
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類blog
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類---->Trunkrem
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(); } }
總結:相似於樹型結構,使其部分與總體具備結構上的一致性。
優勢:結構簡便,使其內部結構透明,對於用戶公開
缺點:根節點部分函數未使用。