Six Principles of Design Patterns: Dependency Inversion Principle

Definition : High-level modules should not depend on low-level modules, both should depend on their abstractions; abstractions should not depend on details; details should depend on abstractions.

Example: Mother(narrate(): storytelling), Book(getContent()), Newspager(getContent())

The origin of the problem : class A (mother) directly depends on class B (book), if you want to change class A to depend on class C (newspager), you must modify the code of class A to do so. In this scenario, class A is generally a high-level module responsible for complex business logic ; class B and class C are low-level modules responsible for basic atomic operations ; if class A is modified, it will bring unnecessary risks to the program.

Solution : Modify class A to depend on interface I (IReader), class B and class C implement interface I respectively, and class A indirectly contacts class B or class C through interface I, which will greatly reduce the probability of modifying class A.

Principle : Compared with the variability of details, abstract things are much more stable. Architectures built on abstraction are much more stable than architectures built on details. In Java , abstract refers to an interface or abstract class, and details are specific implementation classes. The purpose of using interfaces or abstract classes is to formulate specifications and contracts, without involving any specific operations, and leave the task of showing details to their implementation class to complete.

Core idea : object-oriented programming.

Advantages : reduce the coupling between classes, improve the stability of the system, and reduce the risk caused by modifying the program.

Extension : There are three ways to transfer dependencies. The method used in the above example is interface transfer , and there are two other transfer methods: constructor transfer and setter method transfer .

In actual programming, we generally need to do the following three points:

  • Low-level modules should try to have abstract classes or interfaces, or both.
  • Variables should be declared as abstract classes or interfaces as much as possible.
  • Follow the Liskov substitution principle when using inheritance.
Reference: http://blog.csdn.net/zhengzhb/article/details/7289269


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325526837&siteId=291194637