什么是依赖倒置原则?为什么它很重要?
当前回答
依赖倒置原则(DIP)就是这么说的
i)高级模块不应该依赖于低级模块。两者都应该依赖于抽象。
ii)抽象永远不应该依赖于细节。细节应该依赖于抽象。
例子:
public interface ICustomer
{
string GetCustomerNameById(int id);
}
public class Customer : ICustomer
{
//ctor
public Customer(){}
public string GetCustomerNameById(int id)
{
return "Dummy Customer Name";
}
}
public class CustomerFactory
{
public static ICustomer GetCustomerData()
{
return new Customer();
}
}
public class CustomerBLL
{
ICustomer _customer;
public CustomerBLL()
{
_customer = CustomerFactory.GetCustomerData();
}
public string GetCustomerNameById(int id)
{
return _customer.GetCustomerNameById(id);
}
}
public class Program
{
static void Main()
{
CustomerBLL customerBLL = new CustomerBLL();
int customerId = 25;
string customerName = customerBLL.GetCustomerNameById(customerId);
Console.WriteLine(customerName);
Console.ReadKey();
}
}
注意:类应该依赖于抽象,如接口或抽象类,而不是特定的细节(接口的实现)。
其他回答
依赖倒置:依赖抽象,而不是具体。
控制反转:主要与抽象,以及主要如何成为系统的粘合剂。
以下是一些关于这方面的好文章:
https://coderstower.com/2019/03/26/dependency-inversion-why-you-shouldnt-avoid-it/
https://coderstower.com/2019/04/02/main-and-abstraction-the-decoupled-peers/
https://coderstower.com/2019/04/09/inversion-of-control-putting-all-together/
这里的其他人已经给出了很好的答案和例子。
DIP之所以重要,是因为它保证了oo原则的“松散耦合设计”。
软件中的对象不应该进入一个层次结构,其中一些对象是顶级对象,依赖于低级对象。底层对象的变化会波及到顶层对象,这使得软件非常容易发生变化。
你希望你的“顶级”对象非常稳定,不容易改变,因此你需要颠倒依赖关系。
基本上它说:
类应该依赖于抽象(例如接口,抽象类),而不是特定的细节(实现)。
如果我们可以假定公司的“高级”员工是通过执行他们的计划来获得报酬的,并且这些计划是由许多“低级”员工的计划的综合执行来交付的,那么我们可以说,如果高级员工的计划描述以任何方式与任何低级员工的具体计划耦合在一起,那么这通常是一个糟糕的计划。
If a high level executive has a plan to "improve delivery time", and indicates that an employee in the shipping line must have coffee and do stretches each morning, then that plan is highly coupled and has low cohesion. But if the plan makes no mention of any specific employee, and in fact simply requires "an entity that can perform work is prepared to work", then the plan is loosely coupled and more cohesive: the plans do not overlap and can easily be substituted. Contractors, or robots, can easily replace the employees and the high level's plan remains unchanged.
“高级”在依赖倒置原则中意味着“更重要”。
依赖倒置原则的一个更清晰的表述方式是:
封装复杂业务逻辑的模块不应该直接依赖于封装业务逻辑的其他模块。相反,它们应该只依赖于简单数据的接口。
也就是说,不是像人们通常做的那样实现你的类逻辑:
class Dependency { ... }
class Logic {
private Dependency dep;
int doSomething() {
// Business logic using dep here
}
}
你应该这样做:
class Dependency { ... }
interface Data { ... }
class DataFromDependency implements Data {
private Dependency dep;
...
}
class Logic {
int doSomething(Data data) {
// compute something with data
}
}
Data和DataFromDependency应该与Logic在同一个模块中,而不是与Dependency在一起。
为什么要这么做?
这两个业务逻辑模块现在已解耦。当Dependency改变时,你不需要改变Logic。 理解Logic所做的是一个简单得多的任务:它只对看起来像ADT的东西起作用。 现在可以更容易地检验逻辑。现在,您可以直接实例化假数据Data并将其传入。不需要模拟或复杂的测试脚手架。