您的位置:首页 > 其它

设计模式之组合模式

2012-12-08 17:14 204 查看
适用于:树结构。整体部分结构。

典型例子:文件夹和文件;JSON库的设计;Swing的容器和组件;

import java.util.ArrayList;
import java.util.List;

public class Test3 {

public static void main(String[] args) {
Component l1 = new Leaf("叶子1");
Component l2 = new Leaf("叶子2");
Component l3 = new Leaf("叶子3");

Component c1 = new Composite("容器1");
Component c2 = new Composite("容器2");

// c1相当于根容器
c1.add(l1);
c1.add(c2);
c2.add(l2);
c2.add(l3);

// 访问根容器。则可以访问到所有节点。 (整体)
System.out.println("访问根容器:");
c1.operation();

// 也可以直接访问容器节点或叶子节点。 (部分)
System.out.println("\n访问容器节点:");
c2.operation();

System.out.println("\n访问容器节点:");
l1.operation();
}

}

interface Component {
void operation();

// 集合操作方法。
// 如果定义在这里,叫做透明的组合模式。如果在客户端需要面向抽象编程,需要使用该种模式。
// 如果定义在容器节点,则叫做安全的组合模式。
void add(Component c);
void remove(Component c);
Component getChild(int i);
}

// 叶子节点
class Leaf implements Component {

private String name;

public Leaf(String name) {
this.name = name;
}

public void operation() {
System.out.println(this.name);
}

// 集合操作方法。叶节点不支持这些操作。

public void add(Component c) {
throw new UnsupportedOperationException();
}
public Component getChild(int i) {
throw new UnsupportedOperationException();
}
public void remove(Component c) {
throw new UnsupportedOperationException();
}

}

// 容器类
class Composite implements Component {

private String name;

public Composite(String name) {
this.name = name;
}

// 持有抽象组件类集合。这样既可以包含叶节点,又可以继续包含容器节点。
private List<Component> children = new ArrayList<Component>();

// 递归遍历
public void operation() {
System.out.println(this.name);
for (Component c : children) {
c.operation();
}
}

// 集合操作方法
public void add(Component c) {
children.add(c);
}

public Component getChild(int i) {
return children.get(i);
}

public void remove(Component c) {
children.remove(c);
}

}


运行结果:

访问根容器:

容器1

叶子1

容器2

叶子2

叶子3

访问容器节点:

容器2

叶子2

叶子3

访问容器节点:

叶子1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: