Java: Inversion of Control (IoC) and dependency injection (DI)

For a long time, I have to inject inversion of control and dependency of these two very vague concept, close your eyes and think about it, there is always a feeling of vertigo. But in order to become a good Java engineer, I spent a week completely clear of them.

01, tight coupling

During our coding, typically requires two or more classes to implement business logic through mutual cooperation, that is, an object needs to get to work with a reference object, if the acquisition process needs its own implementation, coupling of the code will be high, the cost of maintaining them is relatively high.

We come through simulated combat it. If Pharaoh is hosted Shaolin Temple, he wanted to sweep the small two monk Bodhidharma hospital, the code can be achieved.

Small two types of codes are as follows:

public class Xiaoer {
    public void saodi() {
        System.out.println("小二我在扫达摩院的地");
    }
}

Pharaoh class code as follows:

public class Laowang {
    public void mingling() {
        new Xiaoer().saodi();
    }
}

Test class code as follows:

public class Test {

    public static void main(String[] args) {
        Laowang laowang = new Laowang();
        laowang.mingling();
    }

}

Creates an object Xiaoer class mingling method Laowang class using the new keyword - such coupling of the code is high, the cost of maintaining them is very high, why do you say?

One day, the Dharma homes and dirty, and Pharaoh presided think small two monks, the small two monks to practice the Yi Jin Jing, so who is going to sweep it, think of the Pharaoh presided over a small three monks, so Laowang class on I had to the next new command, so the code becomes this:

public class Xiaosan {
    public void saodi() {
        System.out.println("小三我在扫达摩院的地");
    }
}
public class Laowang {
    public void mingling() {
        new Xiaoer().saodi();
    }

    public void mingling1() {
        new Xiaosan().saodi();
    }
}

If the primary three monks to carry water, and perhaps to Pharaoh presided over the command to the small four-monk Bodhidharma hospital to sweep the ground. At this rate, Laowang this class will be mad.

Pharaoh presided over the session monks feel dignified, even sweeping the next command such trouble, he felt very uncomfortable.

02, Inversion of Control

We have to find a way for Pharaoh presided right?

Better to sweep this errand to Pharaoh Young Lao side of it, the old monk is responsible to the petit two little three or four small monk or monks to execute the command of Pharaoh presided. Code can be achieved.

Define a sweeping monk interface code as follows:

public interface Heshang {
    void saodi();
}

Small two types of code changes as follows:

public class Xiaoer implements Heshang {

    @Override
    public void saodi() {
        System.out.println("小二我在扫达摩院的地");        
    }

    public boolean isYijinjing() {
        // 星期三的时候小二和尚要练易筋经
        return false;
    }
}

Three small code changes as follows:

public class Xiaosan implements Heshang {

    @Override
    public void saodi() {
        System.out.println("小三我在扫达摩院的地");        
    }
}

Lao side class code as follows:

public class Laofang {
    public static Heshang getSaodiseng() {
        Xiaoer xiaoer = new Xiaoer();
        if (xiaoer.isYijinjing()) {
            return new Xiaosan();
        }
        return xiaoer;
    }
}

If the old confirmation small two monks practicing Yi Jin Jing, called primary three monks.

Pharaoh class code changes as follows:

public class Laowang {
    public void mingling() {
        Laofang.getSaodiseng().saodi();
    }
}

Test class code does not change, as follows:

public class Test {

    public static void main(String[] args) {
        Laowang laowang = new Laowang();
        laowang.mingling();
    }

}

Pharaoh now is not worry more, just under his command, who called to sweep the hospital by his Dharma Young Lao side to be responsible.

We think this approach for Pharaoh called inversion of control (Inversion of Control, abbreviated as IoC), it is not a technology but an idea - we design a program guide loosely coupled.

Inversion of Control from the meaning of a word can be split into "control" and "reverse" when it comes to control, it is necessary to identify the subject and object, who controls whom; when it comes to reverse, we must know what Forward Yes.

You see, in the case of tightly coupled, under the command of Pharaoh when they have to create an object-dependent (or little two little three monks monk) by the new keyword; and after the inversion of control, Pharaoh looking for sweeping monk by his Young Lao side is responsible, that control over to the Lao side, is not reversed it?

03, Dependency Injection

Dependency injection (Dependency Injection, abbreviated DI) is the main way to achieve control of inversion: In the instance of the class A is created during the creation of the dependent objects B, is determined by the type or name to different objects of different attributes injected . There are three specific about the realization of forms:

1) based constructor. Achieve a particular constructor parameter, when a new object is passed in the object type dependent.

Pharaoh class code changes as follows:

public class Laowang {
    private Heshang saodiseng;

    public Laowang(Heshang saodiseng) {
        this.saodiseng = saodiseng;
    }
    public void mingling() {
       this.saodiseng.saodi();
    }
}

Test class code changes as follows:

public class Test {

    public static void main(String[] args) {
        Laowang laowang = new Laowang(new Xiaosan());
        laowang.mingling();
    }

}

At this time, control is in the hands of test class, it was decided to send little two little three monks monk to perform Pharaoh's sweeping command.

2) Based on the set method. public set method to achieve specific properties, so that the external container calls incoming object type depends.

Pharaoh class code changes as follows:

public class Laowang {
    private Heshang saodiseng;

    public Heshang getSaodiseng() {
        return saodiseng;
    }

    public void setSaodiseng(Heshang saodiseng) {
        this.saodiseng = saodiseng;
    }

    public void mingling() {
       this.getSaodiseng().saodi();
    }
}

Test class code changes as follows:

public class Test {

    public static void main(String[] args) {
        Laowang laowang = new Laowang();
        Xiaosan xiaosan = new Xiaosan();
        laowang.setSaodiseng(xiaosan);
        laowang.mingling();
    }

}

At this time, control remains in the hands of test class, it was decided to send little two little three monks monk to perform Pharaoh's sweeping command.

3) based on the interface. To implement a specific interface for external vessel injection depends of the type of object, which is a more constructor method is more complex and set, where this skip.

Some people will inversion of control equivalent to dependency injection, but in fact they have a fundamentally different: inversion of control is an idea, and dependency injection is a form of control to achieve reversal.

04, Spring Framework

When we figure out the concept of inversion of control and dependency injection, you can look at passing the famous Spring Framework. Inversion of Control is the core Spring framework throughout. Spring dependency injection implemented in two ways: set mode (by value) and the constructor method (reference).

First, we need to add Spring dependency in pom.xml file, code is as follows:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

Secondly, we will Laowang class modified to the following:

public class Laowang {
    private Heshang saodiseng;

    public Laowang(Heshang saodiseng) {
        this.saodiseng = saodiseng;
    }
    public void mingling() {
       this.saodiseng.saodi();
    }
}

Then, we create a Spring configuration file application.xml, something like this:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="laowang" class="com.cmower.java_demo.ioc.Laowang">
    <constructor-arg ref="saodiseng" />
  </bean>

  <bean id="saodiseng" class="com.cmower.java_demo.ioc.Xiaosan" />

</beans>

By element is configured with two objects, a Pharaoh presided over a small three monks, using elements of the small three monks as a constructor parameter Pharaoh hosted.

After the completion of preparations, we have to test the code examples are as follows:

public class Test {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
        Laowang laowang = (Laowang) context.getBean("laowang");
        laowang.mingling();
    }

}

You see, we will hand over control of the IoC framework Spring, so the code can also be the perfect tight coupling solve the problem.

05, finally

in conclusion:

1) Inversion of control is a de-coupling in the software engineering thought, give control to a third party, at run time is determined by the third party will depend on the specific object "injected" into the object call class.

2) Dependency injection as the control inverted one implementation, the instance variables that are passed to the object.

3) By IoC frameworks, class A depends strongly coupled relationship class B can be established at run time through the vessel, that is an example of the transfer of work to create the container B, the class A can just use.

 

Guess you like

Origin www.cnblogs.com/qing-gee/p/11314728.html