UML:如何在Java中实现Association类
我有这个UML Association类。 注意:水平线是实线,垂直线是虚线。
--------- --------- | |*(a) *(b)| | | CLASS |________________| CLASS | |STUDENT | | | COURSE | --------- | --------- |*(c) ______|______ | | | | | CLASS | | TRANSCRIPT | |_____________|
我理解这种关系但我在实现这个UML代码时遇到了一些问题。 我可以实现类Student
和class Course
之间的关系来编码。 这是我的代码:
class Student { Vector b; } class Course { Vector a; }
但是,在课程Transcript
,我不太了解,如何在代码中使用这个类。 它是Student
和Course
的财产。 所以,如果这是真的那么代码将是:
class Student { Vector b; Vector c; } class Course { Vector a; Vector c; }
这是真的吗? 如果这是错的,请教我如何实现这个UML。
谢谢 :)
首先,不要使用Vector,因为它是一个不应该再使用超过10年的旧类。 使用Set
或List
。
如果Transcript
课程包含有关学生参加课程的方式的信息(例如,其订阅课程的日期),您可以像这样实现:
class Student { Set transcripts; } class Transcript { Student student; Course course; Date subscriptionDate; } class Course { Set transcripts; }
这并不妨碍您在Student中提供返回其所有课程的方法:
public Set getCourses() { Set result = new HashSet (); for (Transcript transcript : transcripts) { result.add(transcript.getCourse()); } return result; }
如果Transcript
不包含任何信息,那么它可能会模拟这些类在数据库表中的映射方式,其中两个表之间具有多对多关联的唯一方法是使用包含ID的连接表两个相关表格。
我知道这个问题已经很老了,但我比在关联类中嵌入n..1关系更方便:
public class Transcript { //Transcript's properties } public class Course { private Map transcriptsByStudent; } public class Student { private Map transcriptsByCourse; }
只需添加,在您的模型上,您可以表示关联类的多重性。 这是不必要的,因为关联类是关联本身,并且原始两个类的多重关系将满足。