介绍代码:
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() 逻辑重新登录到一个类,那么我将它们紧密耦合。
有没有更干净的设计方法?