[译]Java 设计模式之组合

(文章翻译自Java Design Pattern: Composite)

组合模式相对来说是比较简单的,但是它在很多设计中被用到,比如SWT、Eclipse工作空间等等。它创建了一个可以通过唯一的方法访问的继承树。

类图

[译]Java 设计模式之组合

下面的代码实现了下面树的结构

[译]Java 设计模式之组合

Java 代码

import java.util.List;
import java.util.ArrayList; //Component
interface Component {
public void show();
} //Composite
class Composite implements Component { private List<Component> childComponents = new ArrayList<Component>(); public void add(Component component) {
childComponents.add(component);
} public void remove(Component component) {
childComponents.remove(component);
} @Override
public void show() {
for (Component component : childComponents) {
component.show();
}
}
} //leaf
class Leaf implements Component {
String name;
public Leaf(String s){
name = s;
}
public void show() {
System.out.println(name);
}
} public class CompositeTest { public static void main(String[] args) {
Leaf leaf1 = new Leaf("1");
Leaf leaf2 = new Leaf("2");
Leaf leaf3 = new Leaf("3");
Leaf leaf4 = new Leaf("4");
Leaf leaf5 = new Leaf("5"); Composite composite1 = new Composite();
composite1.add(leaf1);
composite1.add(leaf2); Composite composite2 = new Composite();
composite2.add(leaf3);
composite2.add(leaf4);
composite2.add(leaf5); composite1.add(composite2);
composite1.show();
}
}
上一篇:线程技术 ☞ Future模式


下一篇:RedHat Linux7.3 使用yum安装时报错,改用CentOS yum源