内容纲要
组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“整体/部分”层次结构。组合模式使得客户端可以统一对待单个对象和组合对象。
以下是一个简单的Java实现:
- 创建组件接口(Component Interface),表示树形结构中的节点:
public interface Component {
void operation();
void add(Component component);
void remove(Component component);
Component getChild(int index);
}
- 创建叶子节点类(Leaf),实现组件接口:
public class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void operation() {
System.out.println("Leaf: " + name);
}
@Override
public void add(Component component) {
throw new UnsupportedOperationException("Leaf elements cannot add components.");
}
@Override
public void remove(Component component) {
throw new UnsupportedOperationException("Leaf elements cannot remove components.");
}
@Override
public Component getChild(int index) {
throw new UnsupportedOperationException("Leaf elements do not have children.");
}
}
- 创建组合类(Composite),实现组件接口,并包含一个组件列表:
import java.util.ArrayList;
import java.util.List;
public class Composite implements Component {
private String name;
private List<Component> components;
public Composite(String name) {
this.name = name;
this.components = new ArrayList<>();
}
@Override
public void operation() {
System.out.println("Composite: " + name);
for (Component component : components) {
component.operation();
}
}
@Override
public void add(Component component) {
components.add(component);
}
@Override
public void remove(Component component) {
components.remove(component);
}
@Override
public Component getChild(int index) {
return components.get(index);
}
}
- 使用组合模式创建对象:
public class Main {
public static void main(String[] args) {
Composite root = new Composite("Root");
Composite branch1 = new Composite("Branch1");
Composite branch2 = new Composite("Branch2");
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
branch1.add(leaf1);
branch2.add(leaf2);
root.add(branch1);
root.add(branch2);
root.operation();
}
}
运行上述代码,你将看到:
Composite: Root
Composite: Branch1
Leaf: Leaf1
Composite: Branch2
Leaf: Leaf2
组合模式让你可以将对象组合成树形结构来表示“整体/部分”层次结构,使得客户端可以统一对待单个对象和组合对象。这种模式在需要表示具有层次结构的数据时非常有用,例如文件系统、图形界面组件和组织结构等。