灵活的结构(Flexible structure)
组合Composite 关于Composite 模式,很重要的一点是,所有属于部分-整体(part-whole)的这些元素都是可以被操作的,也就是说对某个节点(node)/组合(composite)的操作也同样会作用于该节点的所有子节点。GoF在他们的书里给出了如何在基类接口里包含和访问子节点的实现细节,但看起来似乎没这个必要。下面给出的例子,Composite类只是简单继承ArrayList类就实现了包含(子节点)的功能。
//: composite:CompositeStructure.java package composite; import java.util.*; import junit.framework.*; interface Component { void operation(); } class Leaf implements Component { private String name; public Leaf(String name) { this.name = name; } public String toString() { return name; } public void operation() { System.out.println(this); } } class Node extends ArrayList implements Component { private String name; public Node(String name) { this.name = name; } public String toString() { return name; } public void operation() { System.out.println(this); for(Iterator it = iterator(); it.hasNext(); ) ((Component)it.next()).operation(); } } public class CompositeStructure extends TestCase { public void test() { Node root = new Node("root"); root.add(new Leaf("Leaf1")); Node c2 = new Node("Node1"); c2.add(new Leaf("Leaf2")); c2.add(new Leaf("Leaf3")); root.add(c2); c2 = new Node("Node2"); c2.add(new Leaf("Leaf4")); c2.add(new Leaf("Leaf5")); root.add(c2); root.operation(); } public static void main(String args[]) { junit.textui.TestRunner.run(CompositeStructure.class); } } ///:~
上面这种方法可能是“实现composite模式的最简单的方法”,当然这种方法在用于大型系统的时候可能会出现问题。但是,最好的做法可能就是从最简单的方法入手,而只在需要改变它的时候才去优化它。

|