Dependency inversion principle
Definition:
A. High-level modules should not depend on low-level modules. Both of them should depend on abstraction.
B. abstraction should not depend on details. Details should depend on abstraction.
Abstract: an interface or abstract class.
Details: Implementation class, which can be new.
Why should we abide by the Dependency inversion principle?
It is precisely the high-level module that contains the important policy selection and business model in the application. These high-level modules differentiate their applications from others. However, if these high-level modules depend on the lower-level modules, changes to the lower-level modules will directly affect the higher-level modules, forcing them to make changes in turn.
This should be because the policy setting module of the higher level affects the detailed implementation module of the lower layer. Modules that contain high-level business rules should take precedence over those that contain implementation details. In any case, the upper-level modules should not depend on the lower-level modules.
In addition, what we want to be able to reuse is the high-level policy setting module. We are already very good at reusing lower-layer modules in the form of libraries. If a high-level module is independent of a low-level module, it becomes very difficult to reuse the High-Level module in an inaccessible context. However, if a high-level module is independent of a low-level module, it can be easily reused. This principle is the core principle of framework design.
Rules:
The nature of the dependency inversion principle is to make the implementation of each class or module independent from each other through abstraction (abstract class or interface) without affecting each other, so as to implement the loose coupling seen by the module. If you need to use this rule, follow the following rules:
1. Every class has an interface or abstract class, or an abstract class and an interface as much as possible (this is the basic requirement of this principle. Both interfaces and abstract classes are abstract, with abstraction, dependency inversion may be possible );
2. The surface type of the variable should be an interface or abstract class;
3. No class should be derived from a specific class;
4. Try not to override the method of the base class (if the base class is an abstract class and the method has been implemented, try not to override the subclass. Inter-class dependency is abstract, overwriting abstract methods will have a certain impact on the stability of Dependencies );
5. It should be used in combination with the Lee's replacement method;
This principle does not seem very suitable for specific but stable classes. If a class does not change much, it is unlikely to create other derived classes, therefore, relying on it does not seem to cause much harm. For example, the string class.