イントロコード:緩く一方で(少なくとも、私はたい)でなければならない二つの別個のエンティティ(インターフェース/クラス/何でも)を記述しようとするサンプルコードのIMに疎結合例
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();
}
を他方ではお互いに依存し、お互いの知識を必要とする。
上記のシナリオでは、私は実用的なシステムにそれらを実際に結合する第3のクラスが必要です。 student.register(c)は生徒オブジェクトのみを変更し、course.register(s)はコースオブジェクトのみを変更します。統合クラスはs.register(c)とc.register(s)の両方を実行する必要があります。
私はすべてのregister()ロジックを1つのクラスにリロゲートすると、それらを緊密に結合します。
これをよりクリーンな方法で設計できますか?