IOC Control inversion Interpretation (Java)

Source: Internet
Author: User

Quote : IoC (Inversion of control: inverse of controls) is the kernel of the spring container, and the functions of AOP, declarative transactions, and so on, bear fruit on this basis. But the important concept of the IOC is more obscure, it is not easy to let people words too literally, this can not be said to be a great pity. But the IOC does include a lot of content, it's about code decoupling, design patterns, code optimization, and so on, and we're going to use a small example to illustrate the concept.

Understanding the IOC concept through examples

The Lunar New Year has formed a tradition in China, and there are a lot of big-new lunar films in the end. In all the lunar novel, Chang Chih's "Ink attack" is a more brilliant one. The film tells the Warring States Period ink family to help Liang against Zhao aggression of the individual heroism story, magnificent magnificent, muddy and dignified historical scene quite shocked. There is a scene: When Andy Lau played the ink from the arrival of the Liang capital, the City Liang defenders asked: "Who?" Andy Lau replied, "The ink is off!" "We might as well use a Java class to script this" gate inquiry "scenario and understand the IOC concept:
Code Listing 3-1 Moattack: Arranging a script from an actor

Java code
    1. Public class Moattack {
    2. public void Citygateask () {
    3. //① actor directly invades the script
    4. Liudehua LDH = new Liudehua ();
    5. Ldh.responseask ("Ink off!  ");
    6. }
    7. }


We will find the above script in the ①, as the specific role of Andy Lau directly into the script, so that the script and actors directly coupled together (figure 3-1).

A wise screenwriter should revolve around the character of the story when it is created, and should not consider the character's specific actors, so that it is possible to freely select any suitable actor when the script Toupai, rather than being tied to Andy Lau. Through the above analysis, we know that we need to define an interface for the protagonist of the script:
Code Listing 3-2 Moattack: Introducing Script roles

Java code
    1. Public class Moattack {
    2. public void Citygateask ()
    3. {
    4. //① introducing a leather -to-character interface
    5. GeLi GeLi = new Liudehua ();
    6. //② through the interface to carry out the plot
    7. Geli.responseask ("Ink off!    ");
    8. }
    9. }


The role of the script was introduced at ①-GE, the plot of the script was unfolded by the characters, and the characters were played by actors during the filming, as shown in ②. Therefore, the ink attack, leather away, Andy Lau, the class diagram of the Relationship 3 2:

However, from Figure 3 2, we can see that Moattack also relies on the Geli interface and the Liudehua class, and does not achieve what we expect the script to rely solely on the purpose of the role. But the character finally must pass the concrete actor to complete the shooting, how to make Liudehua and the script not related but can complete Geli's concrete action? Of course, in the film Toupai, the director will Liudehua arranged in the role of Geli, the Director will play, characters, actors assembled (figure 3-3).

By introducing the director, the script is decoupled from the specific actor. corresponding to the software, the director is like an assembler, arranging the actors to perform the specific roles.
Now we can explain the IOC concept in turn. The IoC (inverse of control) literally means controlled inversion, which consists of two elements:

    • One is to control
    • The other is reversal.


So what exactly is the "control" being "reversed" ? Corresponding to the previous example, "control" refers to the selection of the Geli role player's control, "inversion" refers to the control from the "Ink attack" script removed, transferred to the director's hands. For software, the selection control of a specific implementation class of an interface is removed from the calling class and transferred to a third-party decision.
Because the IOC was really not straight to the point, the industry had a broad discussion, and the final software industry's leading figure, Martin Fowler, proposed the concept of Di (Dependency injection: Dependency injection) instead of IOC, That is, the dependency of the calling class on an interface implementation class is injected by a third party (container or collaboration Class) to remove the invocation class's dependency on an interface implementation class. The term "Dependency injection" is clearly more straightforward and understandable than "inversion of control".

Types of IOC

From the injection method, the main can be divided into three types: constructor injection, attribute injection and interface injection. Spring supports constructor injection and attribute injection. Let's continue using the examples above to illustrate the differences between the three injection methods.

Constructor Injection

In constructor injection, we pass an interface implementation class through a constructor variable by invoking the constructor of the class, as shown in Listing 3-3:
Code Listing 3-3 Moattack: Injecting leather from the player with a constructor function

Java code
    1. public class moattack  {  
    2.    private geli geli;   
    3.    //① the specific player who injected the leather from   
    4.    public moattack (geli geli) {   
    5.        this.geli = geli;  
    6.    }  
    7.     public  void citygateask () {  
    8.         geli.responseask ( "Ink man leather away! ");   
    9.    }  
    10. }  


Moattack's constructor does not care about who plays the role of the ①, as long as the players who are introduced to the play are required to perform the corresponding performances according to the script. The specific player of the role is arranged by the director, as shown in Listing 3-4:
Code Listing 3-4 Director: Injecting leather from the player with a constructor function

Java code
    1. public class director  {  
    2.    public  void direct () {  
    3.         //① the actor who specified the role   
    4.        geli geli = new  Liudehua ();     
    5.   
    6.          //② inject specific actors into the script   
    7.         moattack moattack = new moattack (geli);    
    8.        moattack.citygateask ();   
    9.    }  
    10. }  


In ①, the director arranges Andy Lau to play the role of the ②, and in the place, Andy Lau "injected" into the script of the Mexican attack, and then began the "gate inquiry" drama performance work.

Attribute Injection

Sometimes, the director will find, although the film "Ink Attack" the first protagonist, but not every scene needs to be a leather, in this case through the constructor injection equivalent to every moment in the presence of the player, it is not appropriate, you can consider using attribute injection. Attribute injection can optionally be used to complete the injection of the invocation class by the setter method, which is more flexible and convenient:
Code Listing 3-5 Moattack: Using setter method to inject leather from player

Java code
  1. Public class Moattack {
  2. private GeLi GeLi;
  3. //① Attribute Injection method
  4. public void Setgeli (GeLi GeLi) {
  5. This.geli = Geli;
  6. }
  7. public void Citygateask () {
  8. Geli.responseask ("Ink Away");
  9. }
  10. }


Moattack provides a setter method for the Geli attribute at ① to allow the director to inject Geli's specific player when needed.
Code Listing 3-6 Director: Using setter method to inject leather from player

Java code
    1. public class director  {  
    2.    public  void direct () {  
    3.        geli geli = new  Liudehua ();   
    4.        moattack moattack =  new moattack ();   
    5.   
    6.          //① Call property setter method to inject   
    7.         moattack.setgeli (Geli);    
    8.         moattack.citygateask ();   
    9.    }  
    10. }   


And through the constructor to inject the leather from the player is different, in the instantiation of the Moattack script, did not specify any player, but after the instantiation of Moattack, when the need to turn off the appearance of the Setgeli () method to inject the actor. In a similar way, we can also provide an injection setter method for other characters in the script, such as Liang, lane-flooded, etc., so that the director can inject the corresponding role according to the different part of the play.

Interface Injection

Extracting all the methods of dependency injection of the calling class into an interface, the calling class provides the appropriate injection method by implementing the interface. In order to take the form of interface injection, you must first declare a actorarrangable interface:

Java code
    1. Public interface Actorarrangable {
    2. void Injectgeli (GeLi GeLi);
    3. }


The moattack then implements the Actorarrangable interface to provide a concrete implementation:
Code Listing 3-7 Moattack: Injecting leather from the player by interface method

Java code
  1. Public class Moattack implements Actorarrangable {
  2. private GeLi GeLi;
  3. //① Implementing interface Methods
  4. public void Injectgeli (GeLi GeLi) {
  5. This.geli = Geli;
  6. }
  7. public void Citygateask () {
  8. Geli.responseask ("Ink Away");
  9. }
  10. }


The director completes the injection of the player through the Actorarrangable Injectgeli () method.
Code Listing 3-8 Director: Injecting leather from the player via interface method

Java code
    1. public class director  {  
    2.    public  void direct () {  
    3.        geli geli = new  Liudehua ();   
    4.        moattack moattack =  new moattack ();   
    5.         moAttack. injectGeli  (Geli);   
    6.         moattack.citygateask ();   
    7.    }  
    8. }  


Because of the additional declaration of an interface through interface injection, the number of classes is increased, and its effect and attribute injection are not fundamentally different, so we do not advocate this approach.

completion of dependency injection through containers

Although Moattack and Liudehua realize decoupling, moattack does not need to focus on the instantiation of the role implementation class, but the work still exists in the code and is only transferred to the Director class. If a producer wants to change the situation, after choosing a script, he wants to choose a director, an actor, a "audition" or a third intermediary to make them perform their duties, and the script, director and actor are decoupled.
The so-called media "auditions" and third-party intermediaries in the program domain is a third-party container that helps to complete the initialization and assembly of classes, allowing developers to detach from the instantiation of these underlying implementation classes, dependency assembly, etc., and focus on more meaningful business logic development efforts. This is undoubtedly a desirable thing, spring is a container that describes the dependencies between classes and classes through configuration files or annotations, automating the initialization of classes and the work of dependency injection. The following is a configuration file fragment of the spring configuration file that is configured for the above instance:

XML code
  1. <? XML version= "1.0" encoding="UTF-8" ?>
  2. <beans xmlns="Http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:p="http://www.springframework.org/schema/p"
  5. xsi:schemalocation= "Http://www.springframework.org/schema/beans
  6. Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
  7. <!--① Implementation class instantiation -
  8. <Bean id= "geli" class="Liudehua"/>
  9. <Bean id= "moattack" class="Com.baobaotao.ioc.MoAttack "
  10. p:geli-ref="Geli"/><!--② build dependencies by Geli-ref -
  11. </Beans>


The container can be started by means of new Xmlbeanfactory ("Beans.xml"). When the container starts, spring automatically instantiates the bean and completes the dependency assembly based on the description of the configuration file, returning the ready-to-use bean instance from the container and then directly using it.
Why does spring have this "magical" power to magically instantiate and assemble the beans that the program uses with a simple configuration file? This "magical" power is attributed to the class reflection capabilities of the Java language itself.

IOC Control inversion Interpretation (Java)

Related Article

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.