組合(Composite)模式的定義:有時又叫作部分-整體模式,它是一種將對象組合成樹狀的層次結構的模式,用來表示“部分-整體”的關係。組合模式使得客戶端代碼可以一致地處理單個對象和組合對象,無須關心自己處理的是單個對象,還是組合對象,這簡化了客戶端代碼;
模式結構
- 頂層抽象:樹枝或者樹葉的抽象接口
- 樹枝:是組合中的葉節點對象,它沒有子節點,用於實現抽象構件角色中 聲明的公共接口。
- 樹葉:是組合中的分支節點對象,它有子節點。它實現了抽象構件角色中聲明的接口,它的主要作用是存儲和管理子部件
源碼導讀
組合模式分爲透明模式和安全模式;透明模式是在頂層抽象中聲明瞭所有管理子對象的方法,樹葉節點點和樹枝節點對於客戶端來說沒有區別。安全模式是在頂層抽象中只聲明葉子和樹枝公有的抽象方法,而將對葉子和樹枝的管理方法實現到對應的類中,因此客戶端就需要區分該節點是樹枝還是葉子從而調用對應的方法。
對組合模式來說,List Set等這些集合類屬於不那麼嚴格的組合模式。由於沒有找到太好的源碼,因此我在這裏分別對透明模式和安全模式組合說明
透明模式:
public abstract class Component{
private String name;
public Component(string name)
{
this.name = name;
}
public abstract boolean Add(Component component);
public abstract boolean Remove(Component component);
public String getName(){
return name;
}
}
public class Branch extend Component{
private List<Component> tree=new ArrayList<>();
public Branch(String name){
super(name);
}
public boolean add(Componet component){
tree.add(component);
return true;
}
public boolean Remove(Component component){
tree.remove(component);
return true;
}
}
public class Leaf extend Component{
public Leaf(String name){
super(name);
}
public boolean add(Componet component){
return false;
}
public boolean Remove(Component component){
return false;
}
}
安全模式:
public abstract class Component{
private String name;
public Component(string name)
{
this.name = name;
}
public String getName(){
return name;
}
}
public class Branch extend Component{
private List<Component> tree=new ArrayList<>();
public Branch(String name){
super(name);
}
public boolean add(Componet component){
tree.add(component);
return true;
}
public boolean Remove(Component component){
tree.remove(component);
return true;
}
public List<Component> getTree(){
return tree;
}
}
public class Leaf extend Component{
public Leaf(String name){
super(name);
}
}
組合模式適用的場景爲需要表述一個系統(組件)的整體與部分的結構層次的場合;組合模式可對客戶端隱藏組合對象和單個對象的不同,以便客戶端可以使用用統一的接口使用組合結構中的所有對象,對於該類場合也適用於組合模式