类图:Stereotype 与 Interface

类图:Stereotype 与 Interface

puml.online

简介 / Introduction

类图(Class Diagram)是面向对象建模的核心工具。除了普通的类之外,Stereotype(构造型)用来标注类的特殊语义,如 <<interface>><<abstract>><<service>>;对应的 UML 概念是接口(Interface)和抽象类(Abstract Class)。本篇分别用 PlantUML 和 Mermaid 展示这些语法的写法。

PlantUML 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
@startuml
skinparam classAttributeIconSize 0

interface "<<interface>>\nIProduct" as IProduct {
+ getPrice(): double
+ getName(): string
}

abstract class "<<abstract>>\nItem" as Item {
+ id: int
+ calculateDiscount(): double
}

class "Product" as Product {
+ price: double
+ name: string
+ getPrice(): double
+ getName(): string
}

class "Service" as Service {
+ fee: double
+ getPrice(): double
}

IProduct <|.. Product : implements
IProduct <|.. Service : implements
Item <|-- Product : extends
@enduml

<<interface>>interface 关键字声明,或在类名上直接写 stereotype。<<abstract>>abstract class 关键字。实现(implements)用点线三角箭头 <|..,继承(extends)用实线三角箭头 <|--

Mermaid 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
classDiagram
class IProduct {
<<interface>>
+ getPrice(): double
+ getName(): string
}

class Item {
<<abstract>>
- id: int
+ calculateDiscount(): double
}

class Product {
+ price: double
+ name: string
+ getPrice(): double
+ getName(): string
}

class Service {
+ fee: double
+ getPrice(): double
}

IProduct <|.. Product : implements
IProduct <|.. Service : implements
Item <|-- Product : extends

Mermaid 的 classDiagram 中,用 <<interface>><<abstract>> 在类名后标注。实现关系同样用 <|..,继承用 <|--。注意 Mermaid 不支持在类内写 + id: int 时加可见性修饰符(- 为 private,+ 为 public)。

对比 / Side-by-side

特性 PlantUML Mermaid
Interface 声明 interface "<<interface>>\nName" 或直接 interface Name class Name { <<interface>> }
Abstract Class 声明 abstract class "<<abstract>>\nName" class Name { <<abstract>> }
实现关系 `< ..`
继承关系 `< –`
属性可见性 + public, - private, # protected + public, - private(仅支持这两种)
皮肤参数 skinparam classAttributeIconSize 0 隐藏图标 不支持皮肤参数

小结 / Wrap-up

Stereotype 是 UML 类图中区分接口、抽象类、服务等角色标记。PlantUML 对 stereotype 的渲染更丰富(可直接写在类名上),Mermaid 则以内联 {<<interface>>} 标注为主。两者实现/继承关系箭头语法一致,均支持 interface 声明,选用时根据团队工具链和图表定制需求决定。

  • 标题: 类图:Stereotype 与 Interface
  • 作者: puml.online
  • 创建于 : 2026-09-02 08:00:00
  • 更新于 : 2026-09-02 01:06:39
  • 链接: https://puml.online/blog/class-diagram-stereotypes/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。