PlantUML 类图语法教程
# PlantUML 类图语法教程
PlantUML 是一个开源工具,使用简单的文本描述来绘制 UML 图。本文将介绍如何使用 PlantUML 绘制类图。
## 基本语法
### 1. 类定义
使用 `@startuml` 和 `@enduml` 包裹图表内容:
```plantuml
@startuml
class Animal {
+String name
+int age
+void eat()
}
@enduml
```
### 2. 类成员
类成员包括属性和方法,使用以下符号表示可见性:
| 符号 | 含义 |
|------|------|
| `-` | Private(私有) |
| `#` | Protected(受保护) |
| `~` | Package(包内) |
| `+` | Public(公有) |
### 3. 完整示例
```plantuml
@startuml
skinparam monochrome true
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 : 继承
@enduml
```
## 关系类型
PlantUML 支持以下类关系:
| 语法 | 关系类型 | 说明 |
|------|----------|------|
| `<|--` | 继承 | A 继承自 B |
| `*--` | 组合 | 强拥有关系 |
| `o--` | 聚合 | 弱拥有关系 |
| `-->` | 关联 | 一般关联 |
| `--` | 链接 | 实线连接 |
| `..>` | 依赖 | 虚线箭头 |
| `..|>` | 实现 | 接口实现 |
## 多重性标注
可以在关系上标注多重性:
```plantuml
@startuml
Animal "1" --> "many" Food : 吃
Student "n" --> "1" Class : 属于
@enduml
```
## 接口和抽象类
### 接口
```plantuml
@startuml
interface IShape {
+double area()
+double perimeter()
}
class Circle implements IShape {
+double radius
+double area()
+double perimeter()
}
@enduml
```
### 抽象类
```plantuml
@startuml
abstract class Shape {
+String color
+abstract double area()
}
class Rectangle extends Shape {
+double width
+double height
+double area()
}
@enduml
```
## 注释
使用 `note` 添加注释:
```plantuml
@startuml
class Animal {
+String name
}
note right of Animal : 这是所有动物的基类
@enduml
```
## 包和命名空间
```plantuml
@startuml
package "Animals" {
class Animal {
+String name
}
class Dog {
+void bark()
}
}
Animal <|-- Dog
@enduml
```
## 样式设置
### 主题
```plantuml
@startuml
skinparam monochrome true
' 或使用其他主题
' skinparam rose
@enduml
```
### 自定义样式
```plantuml
@startuml
skinparam class {
BackgroundColor White
ArrowColor Black
BorderColor Black
}
@enduml
```
## 实用技巧
### 1. 泛型
```plantuml
@startuml
class "List" {
+add(T item)
+T get(int index)
}
@enduml
```
### 2. 静态成员
```plantuml
@startuml
class Shape {
+{static} int count
+{abstract} double area()
}
@enduml
```
### 3. 枚举
```plantuml
@startuml
enum Color {
RED
GREEN
BLUE
}
@enduml
```
### 4. 关系标签位置
```plantuml
@startuml
class A {}
class B {}
A --> B : 关联 > ' 箭头在右边
A <-- B : 关联 < ' 箭头在左边
@enduml
```
## 布局方向
使用 `left to right direction` 改变布局:
```plantuml
@startuml
left to right direction
class A {}
class B {}
A --> B
@enduml
```
## 隐藏关系
```plantuml
@startuml
class A {}
class B {}
hide A B ' 隐藏类
' hide empty members ' 隐藏空成员
@enduml
```
## 总结
PlantUML 功能强大,支持多种 UML 图表类型。通过本文的学习,你应该能够:
1. 定义类、接口、抽象类
2. 表示各种类关系
3. 添加多重性标注和注释
4. 使用包和命名空间组织类
5. 自定义图表样式
更多语法请参考 [PlantUML 官方文档](https://plantuml.com/zh/class-diagram)。
---
> 本文由 [yanleaf.com](https://yanleaf.com) 提供,转载请注明出处。
评论区