This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

Dependence Inversion Principle (DIP) refers to the Principle that in designing code structures, high-level modules should not depend on low-level modules, but both should depend on their abstraction. Abstraction should not depend on details; Details should depend on abstractions. Dependency inversion reduces class-to-class coupling, improves system stability, improves code readability and maintainability, and reduces the risk of modifying programs.

Create a XiaoMing class as an example:

Call:

Xiao Ming may also need to learn Chinese courses. At this time, with the expansion of business, our code needs to be modified from the bottom to the top. Add the studyChinese() method to XiaoMing and call it at the higher level. After this system is released, it is actually very unstable, and it will bring unexpected risks when changing the code. Next, let’s optimize our code and create an abstract interface class for this course called ICourse:

Then write the math class MathematicsCourse:

English class EnglishCourse

Alter class XiaoMing:

Look at the code call:

We will look at the code at this time. No matter what new lessons XiaoMIng has to learn, FOR the new lessons, I just need to create a new class and tell XiaoMIng by passing the reference, without modifying the underlying code. This is actually a very familiar method called dependency injection, and the injection method is constructor method and setter method. Let’s look at constructor injection:

 

Look at the code call:

According to constructor injection, an instance is created each time it is called. So, if XiaoMing is a global singleton, then we have no choice but to use setters to inject and continue to modify the code for XiaoMing:

Look at the code call:

Now look at the final class diagram:

Generally speaking, an architecture based on abstraction is much more stable than one based on detail. Code is designed for interfaces, and the code is structured from the top to the details