将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
理解组合模式:树形结构中单个对象与组合对象拥有统一接口
掌握 Component(抽象组件)、Leaf(叶子)、Composite(组合)的核心结构
理解透明性 vs. 安全性:Component 接口是否声明 add/remove
了解组合模式在文件系统、UI 组件树、机构组织结构中的应用
组合模式让叶子与容器共用同一接口,客户端可以统一处理树形结构
/** 抽象组件:叶子和组合的共同接口 */
public interface Shape {
void draw();
}/** 叶子节点:点 */
public class Dot implements Shape {
private int x, y;
public Dot(int x, int y) { this.x = x; this.y = y; }
public void draw() {
System.out.println("Drawing Dot at (" + x + "," + y + ")");
}
}/** 叶子节点:圆 */
public class Circle implements Shape {
private int x, y, r;
public Circle(int x, int y, int r) {
this.x = x; this.y = y; this.r = r;
}
public void draw() {
System.out.println("Drawing Circle at (" + x + "," + y
+ ") r=" + r);
}
}/** 叶子节点:矩形 */
public class Rectangle implements Shape {
private int x, y, w, h;
public Rectangle(int x, int y, int w, int h) {
this.x = x; this.y = y; this.w = w; this.h = h;
}
public void draw() {
System.out.println("Drawing Rectangle at (" + x + "," + y
+ ") " + w + "x" + h);
}
}import java.util.ArrayList;
import java.util.List;
/** 组合节点:可包含多个子 Shape,支持递归嵌套 */
public class CompoundShape implements Shape {
private List<Shape> children = new ArrayList<>();
public void add(Shape s) { children.add(s); }
public void remove(Shape s) { children.remove(s); }
public void draw() {
for (Shape child : children) {
child.draw();
}
}
}public class Demo {
public static void main(String[] args) {
CompoundShape scene = new CompoundShape();
scene.add(new Dot(1, 1));
scene.add(new Circle(5, 5, 3));
scene.add(new Rectangle(0, 0, 20, 20));
scene.draw();
}
}Leaf 和 Composite 实现同一 Shape 接口,客户端调用 draw() 时无需关心是 Dot 还是 CompoundShape。
CompoundShape 内部包含 List<Shape>,每个元素可以是 Dot/Circle/Rectangle,也可以是另一个 CompoundShape,形成树形递归。
透明性:Component 声明 add/remove,所有子类都有这些方法(Leaf 空实现),但调用 Leaf.add() 会无效。安全性:Component 不声明,Composite 独有 add/remove,编译期更安全但客户端代码需要类型检查。
文件系统(File + Directory)、UI 组件树(Button + Panel)、组织结构图(Employee + Department)、几何图形编辑器。