3

介绍代码:

public interface Course {

    /**
     * returns the number of units (hours) a specific course is
     */
    public int units();

    /**
     * returns the number of students signed up for the course
     */
    public int numOfStudents();

    /**
     * returns the maximum number of students the course can have signed up to it
     */
    public int maxNumStudents();

    /**
     * returns whether or not the student is enrolled in the course
     */
    public boolean registered(Student s);

    /**
     * enrolls s in the course
     * 
     * @pre     this.registered(s) == false
     * @pre     this.numOfStudents() < this.maxNumStudents()
     * 
     * @post    this.registered(s) == true
     * @post    this.numOfStudents() == $prev(this.numOfStudents()) + 1
     */
    public void register(Student s);

}


public interface Student {

    /**
     * enrolls the student in course c
     * 
     * @pre     c.registered(this) == false
     * @pre     c.numOfStudents() < c.maxNumStudents()
     * @pre     this.totalUnits() + c.units() <= 10
     * 
     * @post    c.registered(s) == true
     * @post    this.totalUnits() == $prev(this.totalUnits()) + c.units()
     */
    public void register(Course c);

    /**
     * return the total number of units this student currently is enrolled in
     * 
     * @pre     true
     * @post    0 <= $ret <= 10
     */
    public int totalUnits();

}

在示例代码中,我试图描述两个单独的实体(接口/类/任何东西),它们一方面应该(我希望,至少)松散耦合,但另一方面确实相互依赖并需要一定的知识彼此的。

在上述情况下,我需要一个真正将它们组合成一个工作系统的第三类。它很难看,因为到目前为止,上面的定义是尽可能松耦合的——student.register(c) 只更改学生对象,而 course.register(s) 只更改课程对象。所以一个统一的类必须同时运行 s.register(c) 和 c.register(s)。

尽管如果我将所有 register() 逻辑重新登录到一个类,那么我将它们紧密耦合。

有没有更干净的设计方法?

4

1 回答 1

4

通过使用接口,您已经降低了具体对象之间的依赖程度,这是一件好事。您的系统需要一些依赖性才能正常工作,因此您必须决定要容忍多少。

考虑您系统中的学生可以注册课程。由于课程是一个接口,因此可以实现许多不同类型的课程,然后学生将能够注册其中的任何一个。只要学生只知道课程界面就可以了。Course 也是一样,它只知道 Student 接口而不知道具体的 Student。

就一件事。在您描述的双向关联的情况下,我喜欢让一方成为关系的所有者。也就是说,我可以决定学生拥有关系,因此,学生可以注册课程,但课程不会注册学生。

然后所有客户端代码将进行一次调用 s.register(c)。Student 中的寄存器将处理关系的反面。这减少了客户端代码了解关系双方的需要。

于 2010-11-27T12:42:17.960 回答