组合模式java代码示例
时间: 2023-07-03 09:04:13 浏览: 89
下面是一个简单的 Java 代码示例,演示了如何使用组合模式:
```java
import java.util.ArrayList;
import java.util.List;
// 定义组件接口
interface Component {
void show();
}
// 定义叶子节点
class Leaf implements Component {
private String name;
public Leaf(String name) {
this.name = name;
}
@Override
public void show() {
System.out.println(name);
}
}
// 定义组合节点
class Composite implements Component {
private String name;
private List<Component> children = new ArrayList<>();
public Composite(String name) {
this.name = name;
}
public void add(Component component) {
children.add(component);
}
@Override
public void show() {
System.out.println(name);
for (Component component : children) {
component.show();
}
}
}
// 测试代码
public class CompositePatternDemo {
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");
Leaf leaf3 = new Leaf("leaf3");
// 组装节点
root.add(branch1);
root.add(branch2);
branch1.add(leaf1);
branch2.add(leaf2);
branch2.add(leaf3);
// 展示节点
root.show();
}
}
```
运行结果:
```
root
branch1
leaf1
branch2
leaf2
leaf3
```
阅读全文