Mermaid 类图语法教程

# Mermaid 类图语法教程 Mermaid 是一个基于 JavaScript 的图表绘制工具,支持使用简单的文本语法来创建各种图表。本文将介绍如何使用 Mermaid 绘制 UML 类图。 ## 基本语法 ### 1. 类定义 使用 `classDiagram` 开头,然后定义类: ```mermaid classDiagram class Animal { +String name +int age +void eat() } ``` ### 2. 类成员 类成员包括属性和方法,使用以下符号表示可见性: | 符号 | 含义 | |------|------| | `+` | Public(公有) | | `-` | Private(私有) | | `#` | Protected(受保护) | | `~` | Package/Internal(包内) | ### 3. 完整示例 ```mermaid classDiagram class Animal { +String name +int age #String species -boolean isMammal +void eat() -void sleep() } class Dog { +String breed +void bark() } class Cat { -int lives +void meow() } Animal <|-- Dog : 继承 Animal <|-- Cat : 继承 ``` ## 关系类型 Mermaid 支持以下类关系: | 语法 | 关系类型 | 说明 | |------|----------|------| | `<|--` | 继承 | A 继承自 B | | `*--` | 组合 | 强拥有关系 | | `o--` | 聚合 | 弱拥有关系 | | `-->` | 关联 | 一般关联 | | `--` | 链接 | 实线连接 | | `..>` | 依赖 | 虚线箭头 | | `..|>` | 实现 | 接口实现 | ## 多重性标注 可以在关系上标注多重性: ```mermaid classDiagram Animal "1" --> "many" Food : 吃 Student "n" --> "1" Class : 属于 ``` ## 注释 使用 `note for` 为类添加注释: ```mermaid classDiagram class Animal { +String name } note for Animal "这是所有动物的基类" ``` ## 布局方向 使用 `direction` 设置布局方向: ```mermaid classDiagram direction LR class A {} class B {} A --> B ``` - `TB`:从上到下 - `BT`:从下到上 - `LR`:从左到右 - `RL`:从右到左 ## 命名空间 使用命名空间组织类: ```mermaid classDiagram namespace Animals { class Animal { +String name } class Dog { +void bark() } } Animal <|-- Dog ``` ## 实用技巧 ### 1. 使用泛型 ```mermaid classDiagram class List~T~ { +add(T item) +T get(int index) } ``` ### 2. 抽象类和静态成员 ```mermaid classDiagram class Shape { <> +double area()* +static int count$ } ``` - `<>`:抽象类 - `*`:抽象方法 - `$`:静态成员 ### 3. 回调函数 ```mermaid classDiagram class Callback { +void onSuccess() +void onError() } ``` ## 总结 Mermaid 语法简洁直观,非常适合快速绘制 UML 类图。通过本文的学习,你应该能够: 1. 定义类和类成员 2. 表示各种类关系 3. 添加多重性标注 4. 使用注释和命名空间 更多语法请参考 [Mermaid 官方文档](https://mermaid.js.org/intro/syntax-reference.html)。 --- > 本文由 [yanleaf.com](https://yanleaf.com) 提供,转载请注明出处。
作者: demo_test 发布时间: 2026-04-14 22:39:11 阅读数: 1 点赞数: 0 评论数:

评论区

备案期间,评论功能暂时关闭。