Oop DI原则和“直接投资”原则有什么区别;程序到接口,而不是实现;?
我不理解依赖倒置和Gof书中的著名短语“程序到接口,而不是实现”之间的区别。 DIP的定义说明了以下原则:Oop DI原则和“直接投资”原则有什么区别;程序到接口,而不是实现;?,oop,inversion-of-control,Oop,Inversion Of Control,我不理解依赖倒置和Gof书中的著名短语“程序到接口,而不是实现”之间的区别。 DIP的定义说明了以下原则: 高级模块不应依赖于低级模块。两者都应该依赖于抽象 抽象不应该依赖于细节。细节应该取决于抽象 这两个原则似乎做了相同的事情:将接口与实现分离。在OOP中,“程序到接口,而不是到实现”是一个一般意义上的好建议(即使您的语言不支持接口的概念)。其思想是,发送消息的对象不应该关心接收者的具体情况(例如,哪个类是实例,或者它是否属于给定的层次结构),只要它能够回答一组消息(从而执行一组行为)。如果您
HTH假设您有一台
计算机
类
定义如下:
public class Computer
{
public string OwnerName{get; set;}
public int RAMCapacity{get; set;} //Hardware based property
public string OperatingSystem{get; set;} //Software based property
}
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
}
public void SetHardware(IHardwareComponents comp)
{
comp.RAMCapacity = 512;
}
现在,编程到接口
表示,根据上述代码注释,您应该创建一个ISOFTWARE组件
和IHardwareComponents
接口,并将这些属性移动到相应的接口,并在计算机
类中实现这两个接口,如下所示:
public class Computer
{
public string OwnerName{get; set;}
public int RAMCapacity{get; set;} //Hardware based property
public string OperatingSystem{get; set;} //Software based property
}
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
}
public void SetHardware(IHardwareComponents comp)
{
comp.RAMCapacity = 512;
}
现在,计算机
类的客户端代码可以使用如下代码:
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 class Computer
{
public string OwnerName{get; set;}
public int RAMCapacity{get; set;} //Hardware based property
public string OperatingSystem{get; set;} //Software based property
}
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
}
public void SetHardware(IHardwareComponents comp)
{
comp.RAMCapacity = 512;
}
对以上示例进行更多探索,您将了解更多