UML:如何在Java中实现Association类

时间:2012-11-18 19:29:11

标签: java associations uml

我有这个UML Association类。请注意:水平线是实线,垂直线是虚线。

 ---------                  ---------
|         |*(a)        *(b)|         |
| CLASS   |________________|  CLASS  |
|STUDENT  |     |          |  COURSE |
 ---------      |           ---------
                |*(c)
          ______|______
         |             |
         |             |
         |  CLASS      |
         | TRANSCRIPT  |
         |_____________|

我理解这种关系但是在实现这个UML代码时遇到了一些问题。我可以实现类Student和类Course之间的关系来编码。这是我的代码:

class Student {
  Vector<Course> b;
}

class Course {
   Vector<Student> a;
}

但是,在课程Transcript,我不太了解,如何在代码中使用这个类。它是StudentCourse类的属性。所以,如果那是真的那么代码将是:

class Student {
  Vector<Course> b;
  Vector<Transcript> c;
}

class Course {
  Vector<Student> a;
  Vector<Transcript> c;
}

这是真的吗?如果这是错误的,请教我如何实现这个UML。

谢谢:)

3 个答案:

答案 0 :(得分:31)

首先,不要使用Vector,因为它是一个不应该再使用超过10年的旧类。使用SetList

如果Transcript课程包含有关学生参加课程的方式的信息(例如,其订阅课程的日期),您可以像这样实施:

class Student {
    Set<Transcript> transcripts;
}

class Transcript {
    Student student;
    Course course;
    Date subscriptionDate;
}

class Course {
    Set<Transcript> transcripts;
}

这并不妨碍您在Student中提供返回其所有课程的方法:

public Set<Course> getCourses() {
    Set<Course> result = new HashSet<Course>();
    for (Transcript transcript : transcripts) {
        result.add(transcript.getCourse());
    }
    return result;
}

如果Transcript不包含任何信息,那么它可能会模拟这些类在数据库表中的映射方式,其中两个表之间具有多对多关联的唯一方法是使用包含两个关联表的ID的连接表。

答案 1 :(得分:4)

我知道这个问题已经很老了,但我比在关联类中嵌入n..1关系更方便:

public class Transcript {
    //Transcript's properties
} 

public class Course {

    private Map<Student, Transcript> transcriptsByStudent;
}

public class Student {

    private Map<Course, Transcript> transcriptsByCourse;
}

答案 2 :(得分:1)

只需添加,在您的模型上,您可以表示关联类的多重性。这是不必要的,因为关联类 IS 关联本身,并且原始两个类的多重关系将满足。