翻译TIPatterns--灵活的结构(Flexible structure)

灵活的结构(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模式的最简单的方法”,当然这种方法在用于大型系统的时候可能会出现问题。但是,最好的做法可能就是从最简单的方法入手,而只在需要的时候才去改变它。


 

目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值