我发现这段代码创建了实现类的对象并将其分配给接口类变量:
Myinterface obj=new MyImplementationClass();
为什么我们不直接使用
MyImplementationClass obj=new MyImplementationClass();
?
我发现这段代码创建了实现类的对象并将其分配给接口类变量:
Myinterface obj=new MyImplementationClass();
为什么我们不直接使用
MyImplementationClass obj=new MyImplementationClass();
?
实现的类可能不止一个MyInterface
。如果您使用:
MyInterface obj = new MyImplementationClass();
你也可以这样做:
MyInterface obj = new MyOtherImplementationClass();
但是如果你使用具体的实现名称,你就不能这样做(*):
// This wouldn't work:
MyImplementationClass obj = new MyOtherImplementationClass();
而且您将无法使用以下内容:
MyInterface obj = new MyInterface();
因为你不知道什么是instantiate。应该是一个MyInterfaceImplementation
?应该是MyOtherInterfaceImplementation
吗?
但是有一种技术叫做依赖注入。这让您以某种方式将特定实现绑定到type。有了它,您可以执行以下操作:
MyInterface obj = dependencyInjectionContainer.Resolve<MyInterface>();
看看什么是依赖注入?.
(*) 除非MyOtherImplementationClass
继承自MyImplementationClass
.
首先你不能创建接口对象。使用接口的第二点可帮助您以最少的更改迁移到新的类实现
就像在编码的地方一样,您将针对 Interface 而不是类,因此如果明天您更改了 Concrete 类,您只需要在一个地方修改它,所有代码都会切换到新类。