Home Java javaTutorial Detailed examples of dependency inversion principle in Java

Detailed examples of dependency inversion principle in Java

Aug 11, 2017 am 10:12 AM
java in principle

This article mainly introduces the definition of Java dependency inversion principle and the solution to the problem. Friends who are interested should take a look

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.

Origin of the problem: Class A directly depends on class B. If you want to change class A to depend on class C, you must modify the code of class A. In this scenario, class A is generally a high-level module responsible for complex business logic; classes B and 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, class B and class C each implement interface I, class A indirectly contacts class B or class C through interface I, then It will greatly reduce the chance of modifying Category A.

The dependency inversion principle is based on the fact that abstract things are much more stable than the variability of details. An architecture built on abstraction is much more stable than an architecture built on details. In Java, abstraction refers to interfaces or abstract classes, 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, leaving the task of showing the details to Their implementation class to complete.

The core idea of ​​the dependency inversion principle is interface-oriented programming. We still use an example to illustrate how interface-oriented programming is better than implementation-oriented programming. The scene is like this. A mother tells a story to her child. As long as she is given a book, she can tell the story to her child according to the book. The code is as follows:


class Book{ 
 public String getContent(){ 
  return "很久很久以前有一个阿拉伯的故事……"; 
 } 
} 
class Mother{ 
 public void narrate(Book book){ 
  System.out.println("妈妈开始讲故事"); 
  System.out.println(book.getContent()); 
 } 
} 
public class Client{ 
 public static void main(String[] args){ 
  Mother mother = new Mother(); 
  mother.narrate(new Book()); 
 } 
}
Copy after login

Running results:

Mom starts telling stories

A long time ago There is an Arab story...

It is running well. If one day, the demand becomes like this: instead of giving a book, give a newspaper, and let the mother tell the story in the newspaper. The newspaper The code of , actually you have to modify Mother to read it. What if I need to switch to a magazine in the future? What about replacing it with a web page? You have to constantly modify the Mother, which is obviously not a good design. The reason is that the coupling between Mother and Book is too high, and the coupling between them must be reduced.


We introduce an abstract interface IReader. Readings, as long as they have words, are readings:


class Newspaper{ 
 public String getContent(){ 
  return "林书豪38+7领导尼克斯击败湖人……"; 
 } 
}
Copy after login

Run results:


Mom starts telling stories

A long time ago An Arab story...

Mom starts telling the story


Jeremy Lin helped the Knicks defeat the Hawks with 17+9...

Modified like this Finally, no matter how the Client class is extended in the future, there is no need to modify the Mother class. This is just a simple example. In actual situations, the Mother class representing the high-level module will be responsible for completing the main business logic. Once it needs to be modified, the risk of introducing errors is extremely high. Therefore, following the dependency inversion principle can reduce the coupling between classes, improve the stability of the system, and reduce the risks caused by modifying the program.
The adoption of the dependency inversion principle brings great convenience to multi-person parallel development. For example, in the above example, when the Mother class and the Book class were directly coupled, the Mother class must wait until the Book class coding is completed. Coding can be done because the Mother class depends on the Book class. The modified programs can be started at the same time without affecting each other, because the Mother and Book classes have nothing to do with each other. The more people involved in collaborative development and the larger the project, the more significant it is to adopt the dependency-causing principle. The now popular TDD development model is the most successful application of the dependency inversion principle.


There are three ways to transfer dependencies. The method used in the above example is interface transfer. There are also two transfer methods: constructor method transfer and setter method transfer. I believe those who have used the Spring framework, You must be familiar with the way dependencies are passed.

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


Low-level modules must have abstract classes or interfaces, or both.

  • The declared type of a variable should be an abstract class or interface as much as possible.

  • Follow the Liskov substitution principle when using inheritance.

  • The core of the dependency inversion principle is that we program for interfaces. If we understand interface-oriented programming, we also understand dependency inversion.

The above is the detailed content of Detailed examples of dependency inversion principle in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles