PlantUML绘制类图6大关系记录
泛化(Generalization)
描述继承关系,在Java中使用extends关键字描述

1 2 3 4 5 6 7 8 9 10
| @startuml title 泛化 Generalization class Animal class Dog class Cat
Animal <|-- Dog Animal <|-- Cat
@enduml
|
实现(Realization)
实现一个接口,Java中用impletments关键字描述

1 2 3 4 5 6 7 8 9
| @startuml title 实现 Realization interface FlyBeahvior class Plane class Bird
FlyBeahvior <|.. Plane FlyBeahvior <|.. Bird @enduml
|
聚合(Aggregation)
表示整体由部分组成,但是整体和部分不是强依赖的,整体不存在了部分还是会存在。比如:汽车和轮胎,电脑和配件

1 2 3 4 5 6 7 8 9 10 11 12
| @startuml title 聚合 Aggregation class Computer class Mouse class Monitor class Keyboard
Computer o-- Mouse Computer o-- Monitor Computer o-- Keyboard
@enduml
|
组合(Composition)
和聚合不同,组合中整体和部分是强依赖的,整体不存在了部分也不存在了。比如公司和部门,公司没了部门就不存在了。但是公司和员工就属于聚合关系了,因为公司没了员工还在。

1 2 3 4 5 6 7 8 9 10 11
| @startuml title 组合 Composition
class Company class DeptA class DeptB
Company *-- DeptA Company *-- DeptB
@enduml
|
关联关系(Association)
表示不同类对象之间有关联,这是一种静态关系,与运行过程的状态无关,在最开始就可以确定。因此也可以用 1 对 1、多对 1、多对多这种关联关系来表示。比如学生和学校就是一种关联关系,一个医院可以有很多医生,但是一个医生只属于一个医院,因此这是一种多对一的关系,一个医生可以有多个患者,一个患者只能有一个医生在运行开始之前就可以确定。

1 2 3 4 5 6 7 8 9 10
| @startuml title 关联 Association class Hospital class Doctor class Patient
Hospital "1" - "n" Doctor Doctor "1" - "n" Patient
@enduml
|
依赖(Dependency)
和关联关系不同的是,依赖关系是在运行过程中起作用的。A 类和 B 类是依赖关系主要有三种形式
- A 类是 B 类方法的局部变量
- A 类是 B 类方法的参数
- A 类向 B 类发送消息,从而影响 B 类发生变化

1 2 3 4 5 6 7 8 9
| @startuml title 依赖 Dependency class Eat{ eatFoot(Food) } class Food Eat *.. Food
@enduml
|