当前位置:网站首页>Dependency Inversion Principle

Dependency Inversion Principle

2022-06-24 00:03:00 One night, Nara mountain was at odds

The dependency inversion principle is that programs depend on abstract interfaces , Don't rely on concrete implementation . In short, it requires programming the abstraction , Do not program the implementation , This reduces the coupling between the customer and the implementation module .

For not considering abstraction , The high level relies directly on the low-level code , Requirement changes create type problems

  according to DIP Redesign the code , Completed high level , The relationship between the bottom , The relationship between the bottom layers .

//DishDeal Interface 
public  interface DishDeal{
     void Deal();
}

// Qishanmian implements the interface ( Bottom )
public class QishanNoddle implements DishDeal{
     String name;
     @Override
     public void Deal() {
     }
}
// Clear water surface implementation interface 
public class QingshuiNoddle implements DishDeal{
     String name;
     @Override
     public void Deal() {
     }
}
// Shandong cake implementation interface 
public class ShanDongBing implements DishDeal{
     String name;
     @Override
     public void Deal() {
     }
}


//ChefCooking Interface 
public interface  ChefCooking
{
     void cooking(DishDeal dishdeal);
}

//CheCooking Implementation class 
public class Cooker implements ChefCooking{
     public void cooking(DishDeal dishdeal) {
          dishdeal.Deal();
     }
}



// Ordering system ( high-level )
class Client {
     public static void main(String[] args) {

          ChefCooking Zhang;
          // An interface has multiple implementation classes , according to new To determine the implementation method of the call .
          DishDeal QingShuiNoodle=new QingshuiNoddle();
          Zhang.cooking(QingShuiNoodle);// Clear water surface practice 

          DishDeal QishanNoodle =new QishanNoddle();
          Zhang.cooking(QishanNoodle);// Qishan noodles 
     }
}

Sum up :
① Abstractions should not depend on details , Details should depend on abstractions . Details are stable and abstractions are unstable .
Define multiple abstract classes , Each abstract class has several implementation methods , Then an abstract class should call another abstract class , Instead of directly calling its concrete methods , Because the details are unstable .
Details depend on abstraction, which means , The underlying code should not call each other directly , Instead, it calls the abstract indirectly .
② High level modules should not depend on the underlying modules , Instead, both sides rely on abstraction , That is, high-level dependency abstraction , To complete the function , The bottom layer also relies on abstraction , Ensure that the high-level code does not change with the low-level code .

原网站

版权声明
本文为[One night, Nara mountain was at odds]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206232119486038.html