APP下载

分享:类图的6大关系详解

消息来源:baojiabao.com 作者: 发布时间:2026-05-15

报价宝综合消息分享:类图的6大关系详解

类图

以下类图使用 PlantUML 绘制,更多语法及使用请参考:http://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

2020-01-18 02:49:00

相关文章