UML:如何在 Java 中实现关联类 [英] UML: how to implement Association class in Java
问题描述
我有这个 UML Association 类.注意:水平线为实线,垂直线为虚线.
I have this UML Association class. Note that: horizontal line is a solid line and the vertical line is a dashed line.
--------- ---------
| |*(a) *(b)| |
| CLASS |________________| CLASS |
|STUDENT | | | COURSE |
--------- | ---------
|*(c)
______|______
| |
| |
| CLASS |
| TRANSCRIPT |
|_____________|
我理解这种关系,但在实现此 UML 代码时遇到了一些问题.我可以实现 class Student
和 class Course
之间的关系来编码.这是我的代码:
I understand this relationship but I have met some problems when implement this UML to code. I can implement relation between class Student
and class Course
to code. Here is my code:
class Student {
Vector<Course> b;
}
class Course {
Vector<Student> a;
}
但是,在Transcript
课上,我不太明白,如何在代码中使用这个类.它是Student
和Course
类的属性.所以,如果这是真的,那么代码将是:
But, at class Transcript
, I don't understand so much, how to use this class in code. Is it the property of both class Student
and Course
. So, if that's true then the code will be:
class Student {
Vector<Course> b;
Vector<Transcript> c;
}
class Course {
Vector<Student> a;
Vector<Transcript> c;
}
是真的吗?如果这是错误的,请教我如何实现这个 UML.
Is it true? If this is wrong, please teach me how to implement this UML.
谢谢:)
推荐答案
首先,不要使用 Vector,因为它是一个旧类,不应再使用超过 10 年.使用 Set
或 List
.
First of all, don't use Vector, as it's an old class that shouldn't be used anymore for more than 10 years. Use either a Set
or a List
.
如果 Transcript
类包含有关学生参加课程方式的信息(例如,订阅课程的日期),您可以这样实现:
If the Transcript
class contains information about the way a student attends a course (for example, the date of its subscription to the course), you could implement it like this:
class Student {
Set<Transcript> transcripts;
}
class Transcript {
Student student;
Course course;
Date subscriptionDate;
}
class Course {
Set<Transcript> transcripts;
}
这并不妨碍您在 Student 中提供返回他所有课程的方法:
That doesn't prevent you from providing a method in Student that returns all his courses:
public Set<Course> getCourses() {
Set<Course> result = new HashSet<Course>();
for (Transcript transcript : transcripts) {
result.add(transcript.getCourse());
}
return result;
}
如果 Transcript
不包含任何信息,那么可能需要对这些类在数据库表中的映射方式进行建模,这是在两个表之间建立多对多关联的唯一方法表是使用一个连接表来保存两个关联表的 ID.
If Transcript
doesn't contain any information, then it's probably there to model how these classes would be mapped in database tables, where the only way to have a many-to-many association between two tables is to use a join table holding the IDs of the two associated tables.
这篇关于UML:如何在 Java 中实现关联类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!