java - 依赖倒置原理的内在

标签 java oop solid-principles dependency-inversion

我一直在阅读有关可靠的 OOP 原则 ( Dependency Inversion Principle ) 的内容,但不太明白它是如何工作的。

When one class knows explicitly about the design and implementation of another class, changes to one class raise the risk of breaking the other class.

假设我有一个学生,这取决于类(class),如果我改变类(class),这会对学生产生什么影响。使用 DI 是一样的吗?我的意思是 DI 替换新的运算符,那么呢?学生仍然取决于类(class)
你能举一些例子吗?
谢谢

public class Student {
.....
private Course course = new Course(); 
}

updated 1

(场景)如果我假设该类只有默认构造函数,并且它永远不会使用任何实例变量来实例化,如 new Course(name, .......)

updated 2

示例

public class Copy {
    @Autowired
    private Writer writer;
.....
}

public interface Writer{
    void write();
}


public class PrinterWriter implements Writer {
.....
}

public class DiskWriter implements Writer {
....
}

Now what happens is that our copy module needs to know about a printer and a disk, you can imagine those magical if-else statements that come to rescue us in these situations. As the new requirements emerge along the way, you probably add more and more dependencies to this copy module. At the end of the day, you would end up with a very complex, hard to maintain and hard to understand design.

您能否在这个示例中通过简单的示例展示具体的依赖倒置消除了神奇的 if-else 语句的使用

最佳答案

假设一个场景,Course 肯定必须修改构造函数。比方说,正在添加一个新参数,并且 Course 类中没有默认构造函数。

public class Course{
  public Course(String name){}
}

现在 Student 类将出现编译器错误。

public class Student {
   private Course course = new Course(); //ERROR !! no such constructor exist 
}

通过 DI,这就是使用构造函数实现 Student 类的方式:

public class Student {
   private Course course;
   public Student(Course course){
      this.course=course;
   }
}

所以在这里,无论Course发生什么变化,类Student都保持不变。使用属性修改器或字段 getter-setter 方法也可以完成相同的操作。

编辑: 还有其他几种情况,您的 Student 类需要更改。引入新类(class)类型的要求可选强制先决条件。使用数据库或其他数据源中的值创建Course实例。通过 IDE 等工具进行代码重构。

关于java - 依赖倒置原理的内在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41322830/

相关文章:

c# - 如何获取所有实现相同接口(interface)的类?

java - 如何获取 OkHttp3 重定向的 URL?

java - Java 中的上下文切换

oop - Love2D(Lua)中的面向对象编程

php - 加入在用户名 INSERT POST 中生成唯一 ID

c# - 这是单一职责原则的一个例子吗?

java - JPA 继承 : Mapped Superclass vs Table Per Class

java - 未知主机异常

javascript - 如何在另一个对象方法中引用一个对象方法

java - 这个先决条件是否违反了里氏替换原则