Two principles have been introduced in the previous
Open Closure principle
Single principle of responsibility
Today we'll look at another principle: the dependency inversion principle, which contains two aspects
A. High-level modules should not be dependent on low levels of modules, they should all rely on abstraction.
B. Abstractions should not be dependent on specifics, but should be dependent on abstraction.
In fact, these two sentences are summed up to rely on the domain abstraction. In Java, the plain is to interface-oriented programming.
Here's a classic example: cars are common now, and a driver's license is available for most cars. But have you ever thought that if every brand of car is different, then you have to re-learn it every time you change a car. Say that each car's operation should have a standard specification, and this specification corresponds to our programming is the interface. All cars should rely on this interface. If you want to use this example, you can understand the benefits of the dependency inversion principle:
The dependency inversion principle can reduce the coupling between classes, improve the stability of the system, reduce the risk caused by concurrent development, and improve the readability and maintainability of the code.
Let's then use the example in the JDK to illustrate:
Look at the following section of code:
publicclass Test { publicstaticvoidmain(String[] args) { List list=new ArrayList(); list.add("11"); System.out.println(list.get(0)); }}
This code we run is definitely output 11; Next we modify the code
publicclass Test { publicstaticvoidmain(String[] args) { List list=new LinkedList();//list改成linkedList list.add("11"); System.out.println(list.get(0)); }}
The code is still working, because both ArrayList and LinkedList implement the list interface, and we can use them all as lists, which is the benefit of interface-oriented programming. This involves another principle: the Richter substitution principle says that where any base class can appear, subclasses must be able to appear. It's easy to understand that everyone has been using it, and I'm not going to dwell on it. All right, that's it for today. Next time we may be able to talk about specific design patterns.
Copyright NOTICE: This article is the original blog article, reproduced please indicate the source
Basic principles of Java Design Patterns