十一 灵活的结构

灵活的结构(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/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值