1?組合模式:
整體-部分模式,它是一種將對象組合成樹狀層次結構的模式,用來表示整體和部分的關系,使用戶對單個對象和組合對象具有一致的訪問性,屬于結構型設計模式
1.1 特點:
- 組合模式使得客戶端代碼可以一致的處理單個對象和組合對象
- 更容易在組合體內加入新的對象,客戶端不會因為加入新的對象而改變原代碼,滿足''開閉原則''
1.2 缺點:
- 設計較復雜,客戶端需要花更多的時間理清類之間的關系
- 不容易限制容器中的構建
- 不容易用繼承的方法來增加構件的新功能?
1.3 結構:
- 抽象構件角色:
- 樹葉構件角色:
- 樹枝構件角色/中間構件:?
1.4 組合模式分為透明式的組合模式和安全式的組合模式。?
- 透明式:抽象構件聲明了所有子類中的全部方法,客戶端無需區別樹葉對象和樹枝對象
- 安全式:將管理子構件的方法移到樹枝構件中,抽象構件和樹葉構件沒有對子對象的管理方法
1.5 代碼實現
透明模式
public class CompositePattern {public static void main(String[] args) {Component c0 = new Composite();Component c1 = new Composite();Component leaf1 = new Leaf("1");Component leaf2 = new Leaf("2");Component leaf3 = new Leaf("3");c0.add(leaf1);c0.add(c1);c1.add(leaf2);c1.add(leaf3);c0.operation();}
}
//抽象構件
interface Component {public void add(Component c);public void remove(Component c);public Component getChild(int i);public void operation();
}
//樹葉構件
class Leaf implements Component {private String name;public Leaf(String name) {this.name = name;}public void add(Component c) {}public void remove(Component c) {}public Component getChild(int i) {return null;}public void operation() {System.out.println("樹葉" + name + ":被訪問!");}
}
//樹枝構件
class Composite implements Component {private ArrayList<Component> children = new ArrayList<Component>();public void add(Component c) {children.add(c);}public void remove(Component c) {children.remove(c);}public Component getChild(int i) {return children.get(i);}public void operation() {for (Object obj : children) {((Component) obj).operation();}}
}
樹葉1:被訪問! 樹葉2:被訪問! 樹葉3:被訪問!
安全模式
interface Component {public void operation();
}
public class CompositePattern {public static void main(String[] args) {Composite c0 = new Composite();Composite c1 = new Composite();Component leaf1 = new Leaf("1");Component leaf2 = new Leaf("2");Component leaf3 = new Leaf("3");c0.add(leaf1);c0.add(c1);c1.add(leaf2);c1.add(leaf3);c0.operation();}
}