我不明白的依赖反转并在GOF书中提出了著名的短语之间的差异,“程序接口,而不是实现”。 DIP的定义说明了这些原则:DI原理和“程序到接口,而不是实现”有什么区别?
- 高级模块不应该依赖低级模块。两者都应该依赖于抽象。
- 抽象不应该依赖于细节。细节应该取决于抽象。
看来,这两个原则都做同样的事情:将接口与实现分离。
我不明白的依赖反转并在GOF书中提出了著名的短语之间的差异,“程序接口,而不是实现”。 DIP的定义说明了这些原则:DI原理和“程序到接口,而不是实现”有什么区别?
看来,这两个原则都做同样的事情:将接口与实现分离。
“程序接口,而不是实现”是OOP中一般意义上的(即使你的语言不支持接口的概念)的好建议。这个想法是发送消息的对象不应该关心接收者的具体情况(例如,哪个类是实例的,或者它是否属于给定的层次结构),只要它可以回答一组消息(从而执行一组行为)。如果您看一下GoF中的模式,主要的底线之一是,只要您针对接口进行编程,就可以将目标对象替换为另一个,而无需更改客户端中的任何内容。
关于Dependency Inversion Principle我看到它,就像前理念的具体应用。为了获得灵活性和可重用性,您将编程思想应用于接口而非分层架构中的具体类,目的是将较低层与较高层解耦。
HTH
假设你有一个Computer
class
定义如下:
public class Computer
{
public string OwnerName{get; set;}
public int RAMCapacity{get; set;} //Hardware based property
public string OperatingSystem{get; set;} //Software based property
}
现在,编程Interface
说,按照上面的代码中的注释,你应该建立一个ISoftwareComponents
和IHardwareComponents
接口,然后将这些属性到各自的接口和实现Computer
类,如下两个接口:
public interface ISoftwareComponents
{
string OperatingSystem{get; set;}
}
public interface IHardwareComponents
{
int RAMCapacity{get; set;}
}
public class Computer : ISoftwareComponent, IHardwareComponents
{
public string OwnerName{get; set;}
public int RAMCapacity{get; set;} //IHardwareComponents property
public string OperatingSystem{get; set;} //ISoftwareComponents property
}
现在对于Computer
类客户端代码可以使用这样的代码:
Computer comp = new Computer();
//software requirements can use the below code:
string os = ((ISoftwareComponents)comp).OperatingSystem; // and, other variations by method calls
//hardware requirements can use the below code
int memory = ((IHardwareComponents)comp).RAMCapacity; //and, other variations
您也可以通过计算机的其他类和如下方法只有软件和硬件接口部分:
public void SetHardware(IHardwareComponents comp)
{
comp.RAMCapacity = 512;
}
探索更多关于上面的例子,你会知道更多。