UML类图六种关系说明与Java代码展示

UML类图六种关系说明与Java代码展示

工具信息

  • Enterprise Architect 12

1、UML类图六种关系

  • 1、泛化关系(generalization)
  • 2、实现关系(realize)
  • 3、聚合关系(aggregation)
  • 4、组合关系(composition)
  • 5、关联关系(association)
  • 6、依赖关系(dependency)

这六种关系以及对应的符合是否了解呢,下面我们通过一张很经典的例子来展示一下。

2、例子

uml-class-diagram

  • Vehicle类为一个抽象类
  • Vehicle类下面有两个继承类:Car和Bicycly,它们之间的关系为实现关系,使用带空心箭头的虚线表示;
  • Car与SUV之间也是继承关系,它们之间的关系为泛化关系,使用带空心的实线表示;
  • Car与Engine之间是组合关系,使用实心菱形的实线表示;
  • Student与Class之间是聚合关系,使用空心菱形的实线表示;
  • Student与IdCard之间为关联关系,使用实线表示;
  • Student上学需要骑Bicycle,与Bicycle是一种依赖关系,使用带箭头的虚线表示;

下面详细介绍这六种关系。

3、类之间的关系与Java代码展示

他们可以分为三组来区别对比记忆

  • 实现关系(realize)和泛化关系(generalization)
  • 聚合关系(aggregation)和组合关系(composition)
  • 关联关系(association)和依赖关系(dependency)

3.1、实现关系(realize)和泛化关系(generalization)

其中有的将泛化关系和实现关系合并为一种:一般化关系,在java中可以直接翻译为关键字extends和implements。
共同点:

- 均为继承关系,可以通过is-a来判断,例如: Car is a Vehicle,SUV is a Car

不同点:

- 实现关系代码体现为继承抽象类,比如:Car继承抽象类Vehicle
- 泛化关系代码体现为继承非抽象类,比如SUV继承非抽象类Car

具体代码展示如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 交通工具类
* @author yuech
* @version 1.0
* @created 11-4月-2020 21:40:51
*/
public abstract class Vehicle {

public Vehicle(){

}
}

/**
* 小汽车类
* @author yuech
* @version 1.0
* @created 11-4月-2020 21:40:49
*/
public class Car extends Vehicle {

public Engine engine;
public Tire tire;

public Car(){

}
}

/**
* SUV汽车类
* @author yuech
* @version 1.0
* @created 11-4月-2020 21:40:51
*/
public class SUV extends Car {

public SUV(){

}
}

3.2、聚合关系(aggregation)和组合关系(composition)

共同点:

- 均表示整体由部分构成,Class由Student构成,Car由Engine和Tire
- 代码中均通过成员变量的形式展示

不同点:

- 聚合关系体现整体不存在了,个体仍然能够独立存在。例如:Student聚合Class
- 组合关系体现整体不存在了,个体也不复存在。例如:Engine和Tire组合Car

具体代码展示如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 班级类
* @author yuech
* @version 1.0
* @created 11-4月-2020 21:40:50
*/
public class Class {

public Student student;

public Class(){

}
}

/**
* 小汽车类
* @author yuech
* @version 1.0
* @created 11-4月-2020 21:40:49
*/
public class Car extends Vehicle {

public Engine engine;
public Tire tire;

public Car(){

}
}

3.3、关联关系(association)和依赖关系(dependency)

共同点:

- 均表示两个类直接存在某种联系,比如Student以及IdCard的一对一关联,Student去学校时使用Bicycle。

不同点:

- 关联关系是静态的,强关联关系。通常在代码中通过通过成员变量的形式展示。
- 依赖关系是动态的,临时性的关系。通常在代码中通过类构造方法及类方法的传入参数的形式展示

具体代码展示如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 学生
* @author yuech
* @version 1.0
* @created 11-4月-2020 21:40:50
*/
public class Student {

public IdCard idCard;

public Student(){

}

public void ride(Bicycle bicycle){

}
}