课程大纲 / Lesson 08
Composite 结构型

Composite · 组合

将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

01

理解组合模式:树形结构中单个对象与组合对象拥有统一接口

02

掌握 Component(抽象组件)、Leaf(叶子)、Composite(组合)的核心结构

03

理解透明性 vs. 安全性:Component 接口是否声明 add/remove

04

了解组合模式在文件系统、UI 组件树、机构组织结构中的应用

核心概念
树形部分整体结构统一接口一致性Component-Leaf-Composite递归组合
classDiagram class shape { <<interface>> +draw() } class dot { -x int -y int +draw() } class circle { -x int -y int -r int +draw() } class rectangle { -x int -y int -w int -h int +draw() } class compoundshape { -children list~shape~ +add(shape shape) +remove(shape shape) +draw() } shape <|.. dot shape <|.. circle shape <|.. rectangle shape <|.. compoundshape compoundshape *-- shape

组合模式让叶子与容器共用同一接口,客户端可以统一处理树形结构

点击 Run 绘制组合图形...
/** 抽象组件:叶子和组合的共同接口 */
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,形成树形递归。

◈

透明性 vs. 安全性

透明性:Component 声明 add/remove,所有子类都有这些方法(Leaf 空实现),但调用 Leaf.add() 会无效。安全性:Component 不声明,Composite 独有 add/remove,编译期更安全但客户端代码需要类型检查。

◈

典型应用场景

文件系统(File + Directory)、UI 组件树(Button + Panel)、组织结构图(Employee + Department)、几何图形编辑器。