Basic Principles of java Design Patterns
Two principles have been introduced earlier.
Open and closed Principle
Single Responsibility Principle
Let's take a look at another principle: the Dependency inversion principle, which includes two aspects:
A. High-level modules should not depend on low-level modules. They should all rely on abstraction.
B. abstraction should not depend on specifics, but on abstraction.
In fact, to sum up these two sentences, we need to rely on domain abstraction. In java, interface-oriented programming is required.
The following is a classic example: Nowadays, cars are common. Most cars can drive a driver's license. But have you ever thought that if every brand of car has a different way of driving, you have to re-learn every time you change a car. In other words, each vehicle's operation method should have a standard specification, which corresponds to our programming interface. All vehicles should rely on this interface. Through this example, you can understand the advantages of the dependency inversion principle:
The dependency inversion principle can reduce inter-class coupling, improve system stability, reduce risks caused by parallel development, and improve code readability and maintainability.
Next we will explain it using the jdk example:
See the following code:
public class Test { public static void main(String[] args) { List list=new ArrayList(); list.add(11); System.out.println(list.get(0)); }}
This code is certainly output 11, and then we modify the code.
Public class Test {public static void main (String [] args) {List list = new writable list (); // change list to writable List list. add (11); System. out. println (list. get (0 ));}}
The code is still running normally, because both arrayList and javaslist implement the list interface. We can use them as lists, which is the benefit of interface-oriented programming. This also applies to another principle: In the Rys replacement principle, subclass can certainly appear where any base class can appear. This is easy to understand and everyone has been using it, so I will not elaborate on it. Now, we are here today. Next time, we may talk about the specific design pattern.