类图的6大关系详解

类图

以下类图使用 PlantUML 绘制,更多语法及使用请参考:plantuml.com/

泛化关系 (Generalization)

用来描述继承关系,在 Java 中使用 extends 关键字。

@startuml

title Generalization

class Vihical
class Car
class Trunck

Vihical <|-- Car
Vihical <|-- Trunck

@enduml复制代码

实现关系 (Realization)

用来实现一个接口,在 Java 中使用 implements 关键字。

@startuml

title Realization

interface MoveBehavior
class Fly
class Run

MoveBehavior <|.. Fly
MoveBehavior <|.. Run

@enduml复制代码

聚合关系 (Aggregation)

表示整体由部分组成,但是整体和部分不是强依赖的,整体不存在了部分还是会存在。

@startuml

title Aggregation

class Computer
class Keyboard
class Mouse
class Screen

Computer o-- Keyboard
Computer o-- Mouse
Computer o-- Screen

@enduml复制代码

组合关系 (Composition)

和聚合不同,组合中整体和部分是强依赖的,整体不存在了部分也不存在了。比如公司和部门,公司没了部门就不存在了。但是公司和员工就属于聚合关系了,因为公司没了员工还在。

@startuml

title Composition

class Company
class DepartmentA
class DepartmentB

Company *-- DepartmentA
Company *-- DepartmentB

@enduml复制代码

关联关系 (Association)

表示不同类对象之间有关联,这是一种静态关系,与运行过程的状态无关,在最开始就可以确定。因此也可以用 1 对 1、多对 1、多对多这种关联关系来表示。比如学生和学校就是一种关联关系,一个学校可以有很多学生,但是一个学生只属于一个学校,因此这是一种多对一的关系,在运行开始之前就可以确定。

@startuml

title Association

class School
class Student

School "1" - "n" Student

@enduml

依赖关系 (Dependency)

和关联关系不同的是,依赖关系是在运行过程中起作用的。A 类和 B 类是依赖关系主要有三种形式:

  • A 类是 B 类方法的局部变量;
  • A 类是 B 类方法当中的一个参数;
  • A 类向 B 类发送消息,从而影响 B 类发生变化。
@startuml

title Dependency

class Vihicle {
    move(MoveBehavior)
}

interface MoveBehavior {
    move()
}

note "MoveBehavior.move()" as N

Vihicle ..> MoveBehavior

Vihicle .. N

@enduml复制代码



转载于:https://juejin.im/post/5cfe0563e51d457753138197

猜你喜欢

转载自blog.csdn.net/weixin_33968104/article/details/93170773
今日推荐