组合模式Java实例解析
组合模式(Composite Pattern)是一种结构型设计模式,它允许你将对象组合成树形结构来表示“部分-整体”的层次结构。组合模式使得客户端可以统一地对待单个对象和对象的组合。
在Java中,组合模式通常涉及以下几个角色:
- Component(抽象构件):为树叶构件和树枝构件声明通用接口,并定义一个接口用于访问和管理它的子部件。
- Leaf(叶子构件):表示叶节点对象,叶子节点没有子节点。
- Composite(树枝构件):表示分支节点对象,分支节点可以有子节点。
- Client(客户端):构建和使用组合对象。
下面是一个简单的Java实例,演示了如何使用组合模式:
// Component
abstract class Component {
public void add(Component component) {
throw new UnsupportedOperationException();
}
public void remove(Component component) {
throw new UnsupportedOperationException();
}
public Component getChild(int index) {
throw new UnsupportedOperationException();
}
public abstract void display(int depth);
}
// Leaf
class Leaf extends Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void display(int depth) {
System.out.println("-" + "-".repeat(depth) + name);
}
}
// Composite
class Composite extends Component {
private List children = new ArrayList<>();
private String name;
public Composite(String name) {
this.name = name;
}
@Override
public void add(Component component) {
children.add(component);
}
@Override
public void remove(Component component) {
children.remove(component);
}
@Override
public Component getChild(int index) {
return children.get(index);
}
@Override
public void display(int depth) {
System.out.println("-" + "-".repeat(depth) + name);
for (Component child : children) {
child.display(depth + 2);
}
}
}
// Client
public class Client {
public static void main(String[] args) {
// 创建根节点
Composite root = new Composite("Root");
// 创建叶子节点
Leaf leaf1 = new Leaf("Leaf1");
Leaf leaf2 = new Leaf("Leaf2");
// 创建子树
Composite subtree1 = new Composite("Subtree1");
Leaf leaf3 = new Leaf("Leaf3");
Leaf leaf4 = new Leaf("Leaf4");
subtree1.add(leaf3);
subtree1.add(leaf4);
// 将叶子节点和子树添加到根节点
root.add(leaf1);
root.add(leaf2);
root.add(subtree1);
// 显示整个树结构
root.display(1);
}
}
在这个例子中,我们定义了一个抽象类Component
,它包含了添加、删除和获取子节点的方法,以及一个抽象的display
方法用于显示节点。Leaf
类表示叶子节点,它实现了display
方法来显示自己的名称。Composite
类表示树枝节点,它可以包含其他组件,并实现了add
、remove
和getChild
方法来管理子节点,同时它的display
方法会递归地显示所有子节点。
客户端代码创建了一个树形结构,并通过调用display
方法来显示整个结构。这个例子展示了如何使用组合模式来统一处理单个对象和对象组合。