简体   繁体   English

具有抽象类的依赖注入

[英]Dependency Injection with an abstract class

Does the Dependency Injection refer only to a case with Interfaces? 依赖注入是否仅涉及接口的情况? Assume we have constructor of the class with parameter declared as Interface so we can pass implementation when creating a class. 假设我们有一个类的构造函数,其参数声明为Interface,因此在创建类时可以通过实现。 The same we can do when we create an abstract class and a class which extends it. 创建抽象类和扩展抽象类的方法相同。 Does the second case could be also named Dependency Injection or this technique refers only to interface usage? 第二种情况是否也可以命名为“依赖注入”,或者该技术仅指接口用法?

Dependency Injection doesn't have a specific deal with interfaces, at all. 依赖注入根本没有对接口的特定处理。 In simplest terms, it just states, inject the damn dependencies at run-time as you want without being controlled by inbuilt compile-time dependencies . 用最简单的话说,它只是在运行时根据需要注入该死的依赖项而不受内置编译时依赖项的控制

It is analogical to something like this. 类似于这样的事情。 I purchase a car with an engine I want without buying a car with an inbuilt engine (engine they want). 我购买了具有所需引擎的汽车,而没有购买具有内置引擎(他们想要的引擎)的汽车。 So it is all about the run time configurability of object creation. 因此,这与对象创建的运行时可配置性有关。

So there's no matter at all whether you are injecting parameter type being an interface, abstract class or even a concrete class. 因此,无论您要注入的参数类型是接口,抽象类还是具体的类,都没有关系。

But anyway though it has no business with DI, if you are using an interface or an abstract class instead of a concrete class type, you can introduce more generalization (via polymorphism) to your code. 但是无论如何,尽管它与DI无关,但是如果您使用接口或抽象类而不是具体的类类型,则可以在代码中引入更多通用性(通过多态性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM