在 Java 中,组合模式(Composite Pattern) 主要用于处理树形结构,让**单个对象(叶子)和组合对象(容器)**对外界使用方式保持一致。
下面从 设计思路 → UML 结构 → Java 示例代码 → 使用场景 一步步说明。
统一对待“部分”和“整体”
| 角色 | 说明 |
|---|---|
| Component | 抽象构件(接口或抽象类) |
| Leaf | 叶子节点 |
| Composite | 组合节点(包含子节点) |
| Client | 使用方 |
public abstract class Component {
protected String name;
public Component(String name) {
this.name = name;
}
public abstract void operation();
// 可选:默认实现,子节点不支持
public void add(Component c) {
throw new UnsupportedOperationException();
}
public void remove(Component c) {
throw new UnsupportedOperationException();
}
}
public class Leaf extends Component {
public Leaf(String name) {
super(name);
}
@Override
public void operation() {
System.out.println("叶子节点: " + name);
}
}
import java.util.ArrayList;
import java.util.List;
public class Composite extends Component {
private List<Component> children = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void add(Component c) {
children.add(c);
}
@Override
public void remove(Component c) {
children.remove(c);
}
@Override
public void operation() {
System.out.println("组合节点: " + name);
for (Component c : children) {
c.operation();
}
}
}
public class Client {
public static void main(String[] args) {
Composite root = new Composite("根");
Leaf leaf1 = new Leaf("叶子1");
Leaf leaf2 = new Leaf("叶子2");
Composite branch = new Composite("分支");
branch.add(new Leaf("叶子3"));
root.add(leaf1);
root.add(branch);
root.add(leaf2);
root.operation();
}
}
组合节点: 根
叶子节点: 叶子1
组合节点: 分支
叶子节点: 叶子3
叶子节点: 叶子2
Composite c = (Composite) component;
c.add(leaf);
✅ 菜单 / 菜单项
✅ 文件 / 文件夹
✅ 组织架构(部门 / 员工)
✅ UI 组件树
✅ XML / JSON 树结构
如果你愿意,我可以:
你更想看哪一种?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。