gpt4 book ai didi

loose-coupling - 松散耦合示例

转载 作者:行者123 更新时间:2023-12-04 06:36:53 26 4
gpt4 key购买 nike

介绍代码:

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();

}

在示例代码中,我试图描述两个独立的实体(接口(interface)/类/其他),一方面应该(我希望,至少)松散耦合,但另一方面确实相互依赖并需要彼此有一定的了解。

在上面的场景中,我需要一个第三类,它实际上将它们联合到一个工作系统中。它很难看,因为到目前为止,上面的定义是尽可能松散耦合的——student.register(c) 只改变学生对象,而 course.register(s) 只改变类(class)对象。所以统一类必须同时运行 s.register(c) 和 c.register(s)。

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

有没有更简洁的设计方法?

最佳答案

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

假设您系统中的学生可以注册类(class)。由于 Course 是一个接口(interface),因此可以实现多种不同类型的 Courses,然后学生将能够注册其中任何一个。只要学生只知道应该没问题的类(class)界面。 Course 也是一样,它只知道 Student 接口(interface),不知 Prop 体的 Students。

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

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

关于loose-coupling - 松散耦合示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4291647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com