Skip to content

类图

¥Class diagrams

"在软件工程中,统一建模语言(UML)中的类图是一种静态结构图,它通过显示系统的类、它们的属性、操作(或方法)以及对象之间的关系来描述系统的结构。"

¥"In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the relationships among objects."

-Wikipedia

类图是面向对象建模的主要构建块。它用于应用结构的一般概念建模,以及将模型转换为编程代码的详细建模。类图也可用于数据建模。类图中的类表示主要元素、应用中的交互以及要编程的类。

¥The class diagram is the main building block of object-oriented modeling. It is used for general conceptual modeling of the structure of the application, and for detailed modeling to translate the models into programming code. Class diagrams can also be used for data modeling. The classes in a class diagram represent both the main elements, interactions in the application, and the classes to be programmed.

Mermaid 可以渲染类图。

¥Mermaid can render class diagrams.

语法

¥Syntax

¥Class

UML 提供了表示类成员(例如属性和方法)以及有关它们的附加信息的机制。图中类的单个实例包含三个部分:

¥UML provides mechanisms to represent class members, such as attributes and methods, and additional information about them. A single instance of a class in the diagram contains three compartments:

  • 顶部隔间包含类的名称。它以粗体居中打印,第一个字母大写。它还可能包含描述类性质的可选注释文本。

    ¥The top compartment contains the name of the class. It is printed in bold and centered, and the first letter is capitalized. It may also contain optional annotation text describing the nature of the class.

  • 中间的部分包含类的属性。它们左对齐且第一个字母小写。

    ¥The middle compartment contains the attributes of the class. They are left-aligned and the first letter is lowercase.

  • 底部隔间包含该类可以执行的操作。它们也是左对齐的,并且第一个字母是小写的。

    ¥The bottom compartment contains the operations the class can execute. They are also left-aligned and the first letter is lowercase.

定义一个类

¥Define a class

定义类有两种方法:

¥There are two ways to define a class:

  • 显式使用关键字 class(如 class Animal)来定义 Animal 类。

    ¥Explicitly using keyword class like class Animal which would define the Animal class.

  • 通过一次定义两个类及其关系的关系。例如,Vehicle <|-- Car

    ¥Via a relationship which defines two classes at a time along with their relationship. For instance, Vehicle <|-- Car.

命名约定:类名只能由字母数字字符(包括 unicode)、下划线和短划线 (-) 组成。

¥Naming convention: a class name should be composed only of alphanumeric characters (including unicode), underscores, and dashes (-).

类别标签

¥Class labels

如果你需要为类提供标签,可以使用以下语法:

¥In case you need to provide a label for a class, you can use the following syntax:

你还可以使用反引号来转义标签中的特殊字符:

¥You can also use backticks to escape special characters in the label:

定义类的成员

¥Defining Members of a class

UML 提供了表示类成员(例如属性和方法)的机制,以及有关它们的附加信息。

¥UML provides mechanisms to represent class members such as attributes and methods, as well as additional information about them.

Mermaid 根据括号 () 是否存在来区分属性和函数/方法。带有 () 的被视为函数/方法,所有其他被视为属性。

¥Mermaid distinguishes between attributes and functions/methods based on if the parenthesis () are present or not. The ones with () are treated as functions/methods, and all others as attributes.

有两种方法可以定义类的成员,无论使用哪种语法来定义成员,输出仍然是相同的。两种不同的方式是:

¥There are two ways to define the members of a class, and regardless of whichever syntax is used to define the members, the output will still be same. The two different ways are :

  • 使用 :(冒号)后跟成员名称来关联类的成员,这对于一次定义一个成员很有用。例如:

    ¥Associate a member of a class using : (colon) followed by member name, useful to define one member at a time. For example:

  • 使用 {} 括号关联类的成员,其中成员分组在大括号内。适合一次定义多个成员。例如:

    ¥Associate members of a class using {} brackets, where members are grouped within curly brackets. Suitable for defining multiple members at once. For example:

返回类型

¥Return Type

或者,你可以使用将返回的数据类型来结束方法/函数定义(注意:最终的 ) 和返回类型之间必须有空格)。一个例子:

¥Optionally you can end a method/function definition with the data type that will be returned (note: there must be a space between the final ) and the return type). An example:

通用类型

¥Generic Types

泛型可以表示为类定义的一部分,也可以表示为类成员/返回类型。为了将该项目表示为通用项,请将该类型括在 ~(波形符)内。支持嵌套类型声明(例如 List<List<int>>),但当前不支持包含逗号的泛型。(如 List<List<K, V>>

¥Generics can be represented as part of a class definition, and for class members/return types. In order to denote an item as generic, you enclose that type within ~ (tilde). Nested type declarations such as List<List<int>> are supported, though generics that include a comma are currently not supported. (such as List<List<K, V>>)

请注意,当在类定义中使用泛型时,泛型类型不被视为类名称的一部分。IE。:对于任何需要引用类名的语法,你需要删除定义的类型部分。这也意味着 mermaid 目前不支持两个具有相同名称但泛型类型不同的类。

¥note when a generic is used within a class definition, the generic type is NOT considered part of the class name. i.e.: for any syntax which required you to reference the class name, you need to drop the type part of the definition. This also means that mermaid does not currently support having two classes with the same name, but different generic types.

能见度

¥Visibility

为了描述属于类(即类成员)的属性或方法/函数的可见性(或封装),可以在该成员名称之前放置可选的符号:

¥To describe the visibility (or encapsulation) of an attribute or method/function that is a part of a class (i.e. a class member), optional notation may be placed before that members' name:

  • + 民众

    ¥+ Public

  • - 私有的

    ¥- Private

  • # 受保护

    ¥# Protected

  • ~ 封装/内部

    ¥~ Package/Internal

请注意,你还可以通过在方法末尾添加以下符号来在方法定义中包含其他分类器,即:在 () 或返回类型之后:

¥note you can also include additional classifiers to a method definition by adding the following notation to the end of the method, i.e.: after the () or after the return type:

  • * 摘要例如:someAbstractMethod()*someAbstractMethod() int*

    ¥* Abstract e.g.: someAbstractMethod()* or someAbstractMethod() int*

  • $ 静态例如:someStaticMethod()$someStaticMethod() String$

    ¥$ Static e.g.: someStaticMethod()$ or someStaticMethod() String$

请注意,你还可以通过在末尾添加以下符号来在字段定义中包含其他分类器:

¥note you can also include additional classifiers to a field definition by adding the following notation to the very end:

  • $ 静态例如:String someField$

    ¥$ Static e.g.: String someField$

定义关系

¥Defining Relationship

关系是一个通用术语,涵盖类图和对象图上发现的特定类型的逻辑连接。

¥A relationship is a general term covering the specific types of logical connections found on class and object diagrams.

[classA][Arrow][ClassB]

目前支持的 UML 下为类定义了八种不同类型的关系:

¥There are eight different types of relations defined for classes under UML which are currently supported:

类型描述
<|--继承
*--作品
o--聚合
-->关联
--链接(实心)
..>依赖
..|>实现
..链接(虚线)

我们可以使用标签来描述两个类之间关系的性质。此外,箭头也可以用于相反的方向:

¥We can use the labels to describe the nature of the relation between two classes. Also, arrowheads can be used in the opposite direction as well:

关系标签

¥Labels on Relations

可以将标签文本添加到关系中:

¥It is possible to add label text to a relation:

[classA][Arrow][ClassB]:LabelText

双向关系

¥Two-way relations

关系在逻辑上可以表示 N:M 关联:

¥Relations can logically represent an N:M association:

语法如下:

¥Here is the syntax:

[Relation Type][Link][Relation Type]

其中 Relation Type 可以是以下之一:

¥Where Relation Type can be one of:

类型描述
<|继承
\*作品
o聚合
>关联
<关联
|>实现

Link 可以是以下之一:

¥And Link can be one of:

类型描述
--实线
..虚线

棒棒糖界面

¥Lollipop Interfaces

类也可以被赋予一个特殊的关系类型,该关系类型在类上定义棒棒糖接口。棒棒糖接口使用以下语法定义:

¥Classes can also be given a special relation type that defines a lollipop interface on the class. A lollipop interface is defined using the following syntax:

  • bar ()-- foo

  • foo --() bar

带有棒棒糖的界面(bar)连接到类(foo)。

¥The interface (bar) with the lollipop connects to the class (foo).

注意:定义的每个接口都是唯一的,并且不应在类之间共享/有多个边缘连接到它。

¥Note: Each interface that is defined is unique and is meant to not be shared between classes / have multiple edges connecting to it.

定义命名空间

¥Define Namespace

命名空间对类进行分组。

¥A namespace groups classes.

关系的基数/多重性

¥Cardinality / Multiplicity on relations

类图中的多重性或基数指示可以链接到另一类的实例的一个类的实例数。例如,每个公司都会有一名或多名员工(不是零),并且每个员工当前为零个或一个公司工作。

¥Multiplicity or cardinality in class diagrams indicates the number of instances of one class that can be linked to an instance of the other class. For example, each company will have one or more employees (not zero), and each employee currently works for zero or one companies.

多重符号放置在关联的末尾附近。

¥Multiplicity notations are placed near the end of an association.

不同的基数选项是:

¥The different cardinality options are :

  • 1 只有 1 个

    ¥1 Only 1

  • 0..1 零或一

    ¥0..1 Zero or One

  • 1..* 一个或多个

    ¥1..* One or more

  • * 许多

    ¥* Many

  • n n(其中 n>1)

    ¥n n (where n>1)

  • 0..n 0 到 n(其中 n>1)

    ¥0..n zero to n (where n>1)

  • 1..n 1 到 n(其中 n>1)

    ¥1..n one to n (where n>1)

通过将文本选项放在给定箭头之前或之后的引号 " 内,可以轻松定义基数。例如:

¥Cardinality can be easily defined by placing the text option within quotes " before or after a given arrow. For example:

[classA] "cardinality1" [Arrow] "cardinality2" [ClassB]:LabelText

类上的注释

¥Annotations on classes

可以使用标记来注释类,以提供有关该类的附加元数据。这可以更清楚地表明其性质。一些常见的注释包括:

¥It is possible to annotate classes with markers to provide additional metadata about the class. This can give a clearer indication about its nature. Some common annotations include:

  • <<Interface>> 表示一个接口类

    ¥<<Interface>> To represent an Interface class

  • <<Abstract>> 表示一个抽象类

    ¥<<Abstract>> To represent an abstract class

  • <<Service>> 代表一个服务类

    ¥<<Service>> To represent a service class

  • <<Enumeration>> 表示一个枚举

    ¥<<Enumeration>> To represent an enum

注释在开头 << 和结尾 >> 内定义。有两种方法可以向类添加注释,两种方法的输出都是相同的:

¥Annotations are defined within the opening << and closing >>. There are two ways to add an annotation to a class, and either way the output will be same:

  • 在定义类之后的单独一行中:

    ¥In a separate line after a class is defined:

  • 在与类定义一起的嵌套结构中:

    ¥In a nested structure along with the class definition:

注释

¥Comments

可以在类图中输入注释,解析器将忽略该注释。注释需要独占一行,并且必须以 %%(双百分号)开头。下一个换行符之前的任何文本都将被视为注释,包括任何类图语法。

¥Comments can be entered within a class diagram, which will be ignored by the parser. Comments need to be on their own line, and must be prefaced with %% (double percent signs). Any text until the next newline will be treated as a comment, including any class diagram syntax.

设置图表的方向

¥Setting the direction of the diagram

对于类图,你可以使用方向语句来设置图渲染的方向:

¥With class diagrams you can use the direction statement to set the direction in which the diagram will render:

相互作用

¥Interaction

可以将单击事件绑定到节点。单击可能会导致 JavaScript 回调或导致在新浏览器选项卡中打开的链接。注意:使用 securityLevel='strict' 时禁用此功能,使用 securityLevel='loose' 时启用此功能。

¥It is possible to bind a click event to a node. The click can lead to either a javascript callback or to a link which will be opened in a new browser tab. Note: This functionality is disabled when using securityLevel='strict' and enabled when using securityLevel='loose'.

声明所有类后,你可以在单独的行上定义这些操作。

¥You would define these actions on a separate line after all classes have been declared.

action className "reference" "tooltip"
click className call callback() "tooltip"
click className href "url" "tooltip"
  • action 是 linkcallback,具体取决于你想要调用的交互类型

    ¥action is either link or callback, depending on which type of interaction you want to have called

  • className 是与操作关联的节点的 id

    ¥className is the id of the node that the action will be associated with

  • Reference 可以是 url 链接,也可以是回调的函数名称。

    ¥reference is either the url link, or the function name for callback.

  • (可选)工具提示是悬停在元素上时显示的字符串(注意:工具提示的样式由 .mermaidTooltip 类设置。)

    ¥(optional) tooltip is a string to be displayed when hovering over element (note: The styles of the tooltip are set by the class .mermaidTooltip.)

  • 注意:将以 nodeId 作为参数调用回调函数。

    ¥note: callback function will be called with the nodeId as parameter.

注意

¥Notes

可以使用 note "line1\nline2" 在图表上添加注释。可以使用 note for <CLASS NAME> "line1\nline2" 为特定类添加注释。

¥It is possible to add notes on the diagram using note "line1\nline2". A note can be added for a specific class using note for <CLASS NAME> "line1\nline2".

示例

¥Examples

网址链接:

¥URL Link:

回调:

¥Callback:

html
<script>
  const callbackFunction = function () {
    alert('A callback was triggered');
  };
</script>

成功 工具提示功能和链接到 URL 的功能从 0.5.2 版本开始提供。

¥The tooltip functionality and the ability to link to urls are available from version 0.5.2.

初学者提示 — 在 HTML 页面中使用交互式链接的完整示例:

¥Beginner's tip—a full example using interactive links in an HTML page:

html
<body>
  <pre class="mermaid">
    classDiagram
    Animal <|-- Duck
    Animal <|-- Fish
    Animal <|-- Zebra
    Animal : +int age
    Animal : +String gender
    Animal: +isMammal()
    Animal: +mate()
    class Duck{
      +String beakColor
      +swim()
      +quack()
      }
    class Fish{
      -int sizeInFeet
      -canEat()
      }
    class Zebra{
      +bool is_wild
      +run()
      }

      callback Duck callback "Tooltip"
      link Zebra "https://www.github.com" "This is a link"
  </pre>

  <script>
    const callback = function () {
      alert('A callback was triggered');
    };
    const config = {
      startOnLoad: true,
      securityLevel: 'loose',
    };
    mermaid.initialize(config);
  </script>
</body>

样式

¥Styling

设置节点样式

¥Styling a node

可以使用 style 关键字将特定样式(例如较粗的边框或不同的背景颜色)应用于单个节点。

¥It is possible to apply specific styles such as a thicker border or a different background color to an individual node using the style keyword.

请注意,注释和命名空间不能单独设置样式,但支持主题。

¥Note that notes and namespaces cannot be styled individually but do support themes.

¥Classes

比每次定义样式更方便的是定义一类样式并将该类附加到应该具有不同外观的节点。

¥More convenient than defining the style every time is to define a class of styles and attach this class to the nodes that should have a different look.

类定义如下例所示:

¥A class definition looks like the example below:

classDef className fill:#f9f,stroke:#333,stroke-width:4px;

此外,还可以在一条语句中为多个类定义样式:

¥Also, it is possible to define style to multiple classes in one statement:

classDef firstClassName,secondClassName font-size:12pt;

将类附加到节点的操作如下:

¥Attachment of a class to a node is done as per below:

cssClass "nodeId1" className;

还可以在一条语句中将一个类附加到节点列表:

¥It is also possible to attach a class to a list of nodes in one statement:

cssClass "nodeId1,nodeId2" className;

添加类的更简短形式是使用 ::: 运算符将类名附加到节点:

¥A shorter form of adding a class is to attach the classname to the node using the ::: operator:

或者:

¥Or:

默认类别

¥Default class

如果某个类名为 default,它将应用于所有节点。应在之后定义特定的样式和类以覆盖应用的默认样式。

¥If a class is named default it will be applied to all nodes. Specific styles and classes should be defined afterwards to override the applied default styling.

classDef default fill:#f9f,stroke:#333,stroke-width:4px;

CSS 类

¥CSS Classes

还可以在 CSS 样式中预定义类,这些类可以从图形定义中应用,如下例所示:

¥It is also possible to predefine classes in CSS styles that can be applied from the graph definition as in the example below:

示例样式

¥Example style

html
<style>
  .styleClass > * > g {
    fill: #ff0000;
    stroke: #ffff00;
    stroke-width: 4px;
  }
</style>

定义示例

¥Example definition

不能同时使用此简写方法和关系语句添加 cssClasses。

¥cssClasses cannot be added using this shorthand method at the same time as a relation statement.

配置

¥Configuration

成员框

¥Members Box

可以隐藏类节点的空成员框。

¥It is possible to hide the empty members box of a class node.

这是通过更改类图配置的 hideEmptyMembersBox 值来完成的。有关如何编辑 Mermaid 配置的更多信息,请参阅 配置页面。

¥This is done by changing the hideEmptyMembersBox value of the class diagram configuration. For more information on how to edit the Mermaid configuration see the configuration page.