Inversion of Control definition
在春季参考中,我们看到:
IoC is also known as dependency injection (DI). It is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method.
我理解正确吗?依赖项是-
1)他们使用的其他对象,仅通过构造函数参数,工厂方法的参数
2)在构造对象实例或从工厂方法返回对象实例后对其设置的属性
请给出这两个项目的简单示例和第二个问题——工厂方法是什么?请详细解释一下。
从这个定义来看,依赖关系是:
other objects they work with
例如,假设您有这个类:
1 2 3 4 5 6 7 | class Widget { public void DoSomething() { WidgetCalculator calculator = new WidgetCalculator(); int someValue = calculator.calculate(); // and so on... } } |
在这个设置中,
这就是依赖倒置变得有用的地方。它不需要创建
1 2 3 4 5 6 | class Widget { public void DoSomething(WidgetCalculator calculator) { int someValue = calculator.calculate(); // and so on... } } |
现在,为了执行该操作,无论调用哪个消耗代码,该操作都需要为
1 2 3 4 5 6 7 8 9 10 11 12 | class Widget { private final WidgetCalculator calculator; public Widget(WidgetCalculator calculator) { this.calculator = calculator; } public void DoSomething() { int someValue = this.calculator.calculate(); // and so on... } } |
提供依赖关系的方式有很多种,但核心原则是,对象需要向其提供依赖关系,而不是寻求依赖关系本身。