组合模式
组合模式,将对象组合成树形结构以表示‘部分-整体’的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。
component为组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认方法。声明一个接口用于访问和管理Component的子部件。
1 package group; 2 3 public abstract class Component { 4 protected String name; 5 6 public Component(String name) { 7 this.name = name; 8 } 9 10 public abstract void add(Component component); 11 12 public abstract void remove(Component component); 13 14 public abstract void display(int depth); 15 }
Leaf类,代表叶子节点
public class Leaf extends Component{ public Leaf(String name) { super(name); } @Override public void add(Component component) { System.out.println("cannot add to a leaf"); } @Override public void remove(Component component) { System.out.println("cannot remove from a leaf"); } @Override public void display(int depth) { StringBuffer buffer = new StringBuffer(); for(int i = 0;i<depth;i++){ buffer.append("-"); } buffer.append(name); System.out.println(buffer.toString()); } }
Composite类,代表分支节点,分支可以有子分支
1 public class Composite extends Component{ 2 3 private List<Component> children = new ArrayList<Component>(); 4 5 public Composite(String name) { 6 super(name); 7 } 8 9 @Override 10 public void add(Component component) { 11 children.add(component); 12 } 13 14 @Override 15 public void remove(Component component) { 16 children.remove(component); 17 } 18 19 @Override 20 public void display(int depth) { 21 StringBuffer buffer = new StringBuffer(); 22 for(int i = 0;i<depth;i++){ 23 buffer.append("-"); 24 } 25 buffer.append(name); 26 System.out.println(buffer.toString()); 27 for(Component c:children){ 28 c.display(depth+2); 29 } 30 } 31 32 }
客户端调用:
1 public class MainClass { 2 public static void main(String[] args) { 3 Component root = new Composite("root"); 4 root.add(new Leaf("Leaf A")); 5 root.add(new Leaf("Leaf B")); 6 7 Composite comp = new Composite("Composite X"); 8 comp.add(new Leaf("Leaf XA")); 9 comp.add(new Leaf("Leaf XB")); 10 11 root.add(comp); 12 13 Composite comp2 = new Composite("Composite XY"); 14 comp2.add(new Leaf("Leaf XYA")); 15 comp2.add(new Leaf("Leaf XYB")); 16 17 comp.add(comp2); 18 19 root.add(new Leaf("Leaf C")); 20 21 Leaf leaf = new Leaf("Leaf D"); 22 root.add(leaf); 23 24 root.remove(leaf); 25 26 root.display(1); 27 } 28 }
像这样,在component中声明了所有用来管理子对象的方法,这样做的好处就是叶子节点和分支节点具有完全一致的行为接口,但问题也很明显,叶子阶段不具备add,remove的行为,所以事先他是没有意义的。另一种安全方式是使二者的行为接口不一致,只在composite中自己实现add,remove的方法。
当需求中是体现部分与整体层次的结构时,就需要用到组合模式了。它让客户可以一致的使用组合结构和单个对象。
每天都要对自己清零,每天都要进步,哪怕只有一点点