Java 组合模式(Composite Pattern) 是 结构型设计模式 的一种,用于把一组相似的对象当作一个单一对象来处理,从而以统一的方式处理单个对象和对象组合。
“树形结构 + 统一接口”
组合模式常用于表示:
✅ 目标:
让客户端对单个对象和组合对象的使用具有一致性
| 角色 | 说明 |
|---|---|
| Component(抽象组件) | 定义统一接口,声明公共操作 |
| Leaf(叶子节点) | 表示叶子对象,没有子节点 |
| Composite(组合节点) | 拥有子组件,实现组件接口,并管理子组件 |
| Client(客户端) | 通过 Component 接口操作对象 |
Component
↑ ↑
Leaf Composite
|
children
public abstract class FileComponent {
protected String name;
public FileComponent(String name) {
this.name = name;
}
public abstract void display();
}
public class File extends FileComponent {
public File(String name) {
super(name);
}
@Override
public void display() {
System.out.println("文件:" + name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Directory extends FileComponent {
private List<FileComponent> children = new ArrayList<>();
public Directory(String name) {
super(name);
}
public void add(FileComponent component) {
children.add(component);
}
public void remove(FileComponent component) {
children.remove(component);
}
@Override
public void display() {
System.out.println("目录:" + name);
for (FileComponent child : children) {
child.display();
}
}
}
public class Client {
public static void main(String[] args) {
File f1 = new File("a.txt");
File f2 = new File("b.txt");
Directory dir = new Directory("文档");
dir.add(f1);
dir.add(f2);
Directory root = new Directory("根目录");
root.add(dir);
root.display();
}
}
✅ 统一处理对象与对象组合
✅ 符合开闭原则(新增节点类型方便)
✅ 适合树形结构,结构清晰
❌ 设计较复杂
❌ 叶子节点可能被迫实现不需要的方法(如 add())
❌ 过度使用会导致系统抽象层次过多
✅ 需要表示 树形结构的对象
✅ 希望对 单个对象和组合对象一视同仁
✅ 如:
组合模式让“单个对象”和“组合对象”拥有相同的接口,从而可以用一致的方式处理它们。
如果你愿意,我也可以帮你:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。