Understanding of the dependency inversion principle (DIP) and IOC, Di, and IOC containers

Source: Internet
Author: User
, Overview

The dependence inversion principle is dependent on abstraction, not specific. Simply put, we need to program the abstraction rather than the implementation, which reduces the coupling between the customer and the implementation module, the concepts such as IOC, Di, and IOC container are extended.

 

2. Intended process-oriented development. The upper layer calls the lower layer, and the upper layer depends on the lower layer. When the lower layer changes dramatically, the upper layer also changes, this will reduce the reusability of modules and greatly increase the development cost. Object-Oriented development solves this problem very well. In general, the probability of abstract changes is very small, so that the user program depends on abstraction, and the Implementation Details also depend on abstraction. Even if the implementation details are constantly changing, the customer program will not need to change as long as the abstraction remains unchanged. This greatly reduces the coupling between customer programs and implementation details. 3. Text

Dependency inversion principle (DIP ):A Software Architecture Design Principle (abstract concept ).

Control reversal (IOC ):A Method for reversing streams, dependencies, and interfaces (specific implementation of DIP ).

Dependency injection (DI ):An Implementation Method of IOC used to reverse the dependency (the specific implementation method of IOC ).

IOC container:Dependency InjectionFrameworkTo map dependencies and manage object creation and lifecycle (di framework ).

 

Let's talk about the dependency inversion principle (DIP) first )":

Here is a small example of life:

All the friends who have received the money know that as long as we have a bank card, we can go to the ATM machines of various banks to withdraw money. In this scenario, the ATM machine belongs to the high-level module, the bank card we have belongs to the underlying module.

A card slot plug-in (Interface) is provided on the ATM for insertion of various bank cards. Here, the ATM does not depend on the specific bank card. It only specifies the specifications of the bank card, as long as the bank card meets this specification parameter, we can use it.

The following concepts are involved in conversion:

The high-level module does not depend on the underlying module, but the underlying module depends on the interfaces of the high-level module (the high-level module defines the interface and the underlying module is responsible for implementation ).

 

High-level module (Interface): Abstraction underlying module (Implementation Interface): Implementation ==> the two should depend on abstraction, abstraction (high-level) independent implementation (underlying), implementation (underlying) dependent on abstraction (high-level ).

 

Here is an example:

1. If the dependency does not result in: the high-level module depends on the underlying module, that is, the underlying module becomes abstract. The high-level module must implement all the abstracted interfaces. Once a new module appears at the underlying layer, you need to modify the high-level module to break the open-closed principle.

2. If Dependency inversion occurs, the underlying module depends on the high-level module. That is to say, the high-level module becomes abstract. The underlying module only needs to implement high-level interfaces. Once a new module appears at the underlying layer, the high-level module does not need to be modified (the abstract interface definition remains unchanged ).

 

This shows the advantages of dip:

The system is more flexible:You can modify part of the code without affecting other modules.

More robust system:You can modify part of the code without causing a system crash.

More efficient system:Components are loosely coupled and reusable to improve development efficiency.

 

 

Next, let's talk about "IOC )":

DIP is a software design principle. It tells us what kind of relationship should be between modules. IOC is a specific software design pattern and tells us how to do it, in order to achieve decoupling between programs.

IOC (control inversion) provides abstraction between high and low-level modules, that is, third-party systems, that is, dependent objects (underlying objects) are not dependent on modules (high-level modules) directly create an object, but hand over the right to create the object to the third IOC container to create it, and then hand over the object to the dependent module (Lenovo just took the money, the ATM machine is a high-level module, it does not decide which bank card to insert itself, such as China Construction Bank or ABC. the right to decide which card to insert lies in US (a third party) and the card to insert, it gives us the services of any bank ).

 

The benefits of IOC are as follows: (the underlying control class of the order system is based on the MySQL database)

Mysqlhelper. Java

1 package COM. LCW. dip. test; 2 3 Public class mysqlhelper {4 5 Public void add () {6 system. out. println ("add order .. "); 7} 8 9 Public void Delete () {10 system. out. println ("delete order .. "); 11} 12 13 public void Update () {14 system. out. println ("Modify order .. "); 15} 16 17 Public void find () {18 system. out. println ("query order .. "); 19} 20}

 

Order. Java

 1 package com.lcw.dip.test; 2  3 public class Order { 4     private MysqlHelper helper = new MysqlHelper(); 5  6     public void addOrder() { 7         this.helper.add(); 8     } 9     10     public void delOrder(){11         this.helper.delete();12     }13     14     public void updateOrder(){15         this.helper.update();16     }17     18     public void FindOrder(){19         this.helper.find();20     }21 }

Diptest. Java

Package COM. LCW. dip. test;/*** Dip (dependence inversion principle) Dependency inversion principle * @ author Balla _ rabbit **/public class diptest {public static void main (string [] ARGs) {order = New Order (); Order. addorder ();}}

Check the operation result:

Perfect, perfect !!

But what should I do if my business needs to be changed to an Access database suddenly?

In traditional practice, we need to write a database operation class on access, modify the code in the order class, and change the instantiated object to the access class.

What if I want to change to an Oracle database in a few days?

..... Repeat and repeat!

 

Is there any way to solve this tedious problem? The answer is yes! Otherwise, I don't need to enter so many words ~~

Next, dependency injection (DI) comes in handy:

Dependency injection is an important way to implement IOC. It grants the creation right of dependent objects to external (third-party) for processing, rather than creating an instance in itself.

For example, in the above Order addition example, when we create a database to manipulate objects, we directly generate new data in the order class. In this case, once the database changes, then we need to modify the order class, which is obviously not desirable and violates the open-closed principle.

What should we do? The answer is obviously to use di (dependency injection) to grant the right to create an object to an external (third-party) for implementation, and then pass it to the module that needs to call the object, that is, the high-level module.

There are three injection methods:

1. constructor injection: Injection Using constructor as its name implies

2. setter method injection: provides a setter method in the class to be injected.

3. Interface injection: Because of code intrusion, it is rarely used. The first two types are mostly used.

 

If you have said so much, go to the code and check the instance directly.

Dbhelper. Java

1 package COM. LCW. dip. test; 2 3 Public class dbhelper {4 5 Public void add () {6 system. out. println ("add order .. "); 7} 8 9 Public void Delete () {10 system. out. println ("delete order .. "); 11} 12 13 public void Update () {14 system. out. println ("Modify order .. "); 15} 16 17 Public void find () {18 system. out. println ("query order .. "); 19} 20}

 

Order. Java

1 package COM. LCW. dip. test; 2 3 Public class order {4 // Private mysqlhelper helper = new mysqlhelper (); 5 private dbhelper helper; 6 Public Order (dbhelper helper) {// provides the constructor, injection property 7 This. helper = helper; 8} 9 10 public void addorder () {11 this. helper. add (); 12} 13 14 public void delorder () {15 this. helper. delete (); 16} 17 18 public void updateorder () {19 this. helper. update (); 20} 21 22 public void findorder () {23 This. helper. find (); 24} 25}

 

Diptest. Java

1 package COM. LCW. dip. test; 2 3/** 4 * Dip (dependence inversion principle) dependency inversion principle 5 * @ author Balla _ rabbit 6*7 */8 public class diptest {9 public static void main (string [] ARGs) {10 // order = New Order (); 11 dbhelper helper = new dbhelper (); 12 order = New Order (helper); // inject dbhelper object 13 order. addorder (); 14} 15 16}

 

The effect remains, so we can easily modify it next time. For example, if we want to change to an Access database, we only need to modify the database manipulation class dbhelper this time, you don't have to change the order class.

Next let's take a look at the injection using the setter method:

 

Dbhelper. Java database operation underlying class unchanged

 

Order. Java

1 package COM. LCW. dip. test; 2 3 Public class order {4 // Private mysqlhelper helper = new mysqlhelper (); 5 // Private dbhelper helper; 6 // public order (dbhelper helper) {// provides the constructor to inject attributes. 7 // This. helper = helper; 8 //} 9 10 private dbhelper helper; 11 Public void sethelper (dbhelper helper) {12 this. helper = helper; 13} 14 15 public void addorder () {16 this. helper. add (); 17} 18 19 public void delorder () {20 this. helper. delete (); 21} 22 23 public void updateorder () {24 this. helper. update (); 25} 26 27 public void findorder () {28 This. helper. find (); 29} 30}

 

Diptest. Java

1 package COM. LCW. dip. test; 2 3/** 4 * Dip (dependence inversion principle) dependency inversion principle 5 * @ author Balla _ rabbit 6*7 */8 public class diptest {9 public static void main (string [] ARGs) {10 // order = New Order (); 11 // dbhelper helper = new dbhelper (); 12 // order = New Order (helper ); // inject dbhelper object 13 dbhelper helper = new dbhelper (); 14 order = New Order (); 15 Order. sethelper (helper); 16 order. addorder (); 17} 18 19}

Effect:

 

Finally, let's talk about the IOC container:

In the preceding example, we create a dependency object manually and then manually pass it to the dependent module (high level). However, for large projects, dependencies between components are very complex. If we still use manual creation of dependency objects and manual injection, it is quite complicated and error-prone, even the status is uncontrollable.

Therefore, the IOC container is born like this, which is a framework of Di to simplify our operations. IOC containers can dynamically create, inject objects, and manage object lifecycles, ing dependencies.

IOC containers include picocontainer, JBoss microcontainer, Soto, and spring.

 

Summary:

DIP is an idea of software design, while IOC is a software design model derived from dip.

Di is one of the specific implementation methods of IOC and is the most widely used.

The IOC container is a DI injection framework that manages the lifecycle and ing relationships of dependencies.

Understanding of the dependency inversion principle (DIP) and IOC, Di, and IOC containers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.