C4 模型:Component 图

C4 模型:Component 图

puml.online

简介 / Introduction

C4 模型是一种用层次化图形表达软件系统架构的方法,从 Context、Container、Component 到 Code 逐层深入。本文聚焦 Component 图,展示同一系统在 PlantUML 和 Mermaid 中的等价表达。


PlantUML 版

PlantUML 通过标准库 !include <C4> 提供完整的 C4 支持,Component 图描述一个 Container 内部由哪些组件构成以及它们的调用关系。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
!include <C4/C4_Container>
!include <C4/C4_Component>

LAYOUT_WITH_LEGEND()

Person(user, "用户", "使用前端应用")
Container(con, "Web 应用", "Java/Spring", "提供业务功能")
ContainerDb(db, "数据库", "PostgreSQL", "存储数据")
Component(auth, "AuthService", "Java", "处理身份验证")
Component(biz, "BizService", "Java", "处理业务逻辑")
Component(repo, "Repository", "Java", "封装数据访问")

Rel(user, con, "使用 HTTPS")
Rel(con, auth, "调用")
Rel(con, biz, "调用")
Rel(biz, repo, "读取/写入")
Rel(repo, db, "JDBC")

SHOW_LEGEND()

Mermaid 版

Mermaid 从 v10 起内置 c4 语法,Component 图的关键字为 C4Context(容器层)和 C4Component。两者的层级关系完全对应。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
c4context
title C4 Component Diagram — Web Application
person(user, "用户", "使用前端应用")
container(con, "Web 应用", "Java/Spring", "提供业务功能")
containerDb(db, "数据库", "PostgreSQL", "存储数据")

component(auth, "AuthService", "Java", "处理身份验证")
component(biz, "BizService", "Java", "处理业务逻辑")
component(repo, "Repository", "Java", "封装数据访问")

Rel(user, con, "使用 HTTPS")
Rel(con, auth, "调用")
Rel(con, biz, "调用")
Rel(biz, repo, "读取/写入")
Rel(repo, db, "JDBC")

对比 / Side-by-side

特性 PlantUML Mermaid
C4 标准库 !include <C4/C4_Container> 内置(无需引入)
组件声明 Component(id, name, tech, desc) component(id, "name", "tech", "desc")
容器声明 Container(id, name, tech, desc) container(id, "name", "tech", "desc")
图例 LAYOUT_WITH_LEGEND() + SHOW_LEGEND() 自动渲染
关系语法 Rel_U/D/L/R 多方向 Rel(sender, receiver, "label")

小结 / Wrap-up

PlantUML C4 通过 !include 引入完整的 C4 标准库,功能丰富但需要后端安装 stdlib 文件;Mermaid C4 是内置语法,开箱即用,适合快速草图。两者生成的图形在语义上完全等价,选择取决于团队已有的工具链。

  • 标题: C4 模型:Component 图
  • 作者: puml.online
  • 创建于 : 2026-09-28 01:00:51
  • 更新于 : 2026-09-29 01:06:38
  • 链接: https://puml.online/blog/c4-diagram-component/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。