概述
是一種結構型模式,將對像以樹形結構組織起來,以表示“部分- 整體”的層次結構,使得客戶端對單個對象和組合對象的使用具有唯一性。
UML類圖
上面的類圖包含的角色:
Component:為參加組合的對象聲明一個公共的接口,不管是組合還是葉節點。
Leaf:在組合中表示葉子結點對象,葉子結點沒有子結點。
Composite:表示參加組合的有子對象的對象,並給出樹枝構建的行為;
代碼示例
import java.util.ArrayList;import java.util.List;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 GetChild(int depth);}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 GetChild(int depth) { String temp = " "; for (int i = 0; i < depth; i++) { temp += "-"; System.out.println(temp + name); } }}class Composite extends Component { private List<Component> children = new ArrayList<>(); 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 GetChild(int depth) { for (Component c : children) { c.GetChild(depth); } }}public class Main { 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.GetChild(3); }}應用場景
1.要求表示對象的部分-整體層次結構。
2.想要客戶端忽略組合對象與單個對象的差異,客戶端將統一地使用組合結構中的所有對象。
組合模式定義由Leaf對象和Composite對象組成的類結構;
使得客戶端變得簡單;
它使得添加或刪除子部件變得很容易。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。