UML中的关系主要分为六种:
- 关联(association)
- 聚合(aggregation)
- 组合(composition)
- 依赖(dependency)
- 泛化(generalization)/继承(inheritance)
- 实现(realization)
根据关系的紧密程度,由小到大顺序是:依赖->关联->聚合->组合
依赖关系
简单理解就是在某个方法里通过传参的方式用到了某个类,例如:
class ImageLoader{
loadImage(ImageInfo info)
}
class ImageInfo{
}
使用UML类图表示该关系:用实心箭头+虚线表示
PlantUML中的表示方法:ImageInfo <… ImageLoader :依赖关系
关联关系
简单理解就是类里面作为属性引用了另一个类,例如:
class Window {
-WindowManager mWindowManager
}
class WindowManager{
}
使用UML类图表示该关系:用实心箭头+实线表示
PlantUML中的表示方法:WindowManager <-- Window:关联关系
聚合关系
表示整体和部分,一个类属性使用列表保存很多个另一个类对象,例如:
class Company{
List<Department> mDepartments
}
class Department{
}
使用UML类图表示该关系:用空心菱形+实线表示
PlantUML中的表示方法:Company o-- Department:聚合关系
组合关系
相比聚合更加紧密的关系,生死与共,不能单独存在,例如:
class Bird{//小鸟
Wing mWing;//翅膀
}
class Wing{//翅膀
}
使用UML类图表示该关系:用实心菱形+实线表示
PlantUML中的表示方法:Bird *-- Wing:组合关系
泛化/继承关系
用来表示类之间的继承关系,例如:
abstract class Factory{
abstract makeProduct()
}
class PhoneFactory extends Factory{
}
class CarFactory extends Factory{
}
使用UML类图表示该关系:用空心箭头+实线表示
PlantUML中的表示方法:Factory <|-- PhoneFactory:泛化关系
实现关系
用来表示一个类实现某个一个接口,例如:
interface IColorDraw{
draw()
}
class RedColorDraw{
draw()
}
class BlueColorDraw{
draw()
}
使用UML类图表示该关系:用空心箭头+虚线表示
PlantUML中的表示方法:IColorDraw <|… RedColorDraw:实现关系
完整的PlantUML表示:
@startuml
class ImageLoader{
loadImage(ImageInfo)
}
class ImageInfo{
}
ImageInfo <.. ImageLoader :依赖关系
class Window {
-WindowManager mWindowManager
}
class WindowManager
WindowManager <-- Window:关联关系
class Company
class Department
Company o-- Department:聚合关系
class Bird
class Wing
Bird *-- Wing:组合关系
abstract class Factory
class PhoneFactory
class CarFactory
Factory <|-- PhoneFactory:泛化关系
Factory <|-- CarFactory:也就是继承关系
interface IColorDraw{
draw()
}
class RedColorDraw{
draw()
}
class BlueColorDraw{
draw()
}
IColorDraw <|.. RedColorDraw:实现关系
IColorDraw <|.. BlueColorDraw:实现某个接口
@enduml