灵活的结构(Flexible structure)
复合(Composite)
这里重要的事是所有在整体-部分中的元素都有操作,并且执行一个操作在一个node/composite同样执行哪个操作在任何子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);
}
} ///:~
然而这种方式看起来“能够工作的最简单的事”,很可能会再大的系统处出现问题。不过,最好是从最简的方式开始并且在需要的时候改变。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/25966/viewspace-53324/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/25966/viewspace-53324/