Factory mode, control inversion, and dependency injection

Source: Internet
Author: User

Before introducing the Factory mode and control inversion (inversion of controls) and dependency injection (Dependency injection), the calling method of the following class is introduced. There are 3 ways to call methods: 1. Create it yourself; 2. Factory mode; 3. External injection, where external injection is the control inversion/Dependency Injection mode (IOC/DI). We can use 3 images to represent them separately, that is, new, get, set. As the name implies, new means to create itself, get means to take the initiative to fetch (that is, the factory), set is sent by someone else (that is, injection), where get and set respectively represents the active to fetch and wait to send two diametrically opposite characteristics, these 3 words represent the thought essence of 3 methods.
Either way, there are two characters, that is, the caller and the callee. Below we explain the specific meanings of these 3 methods through examples. First, we set the calling object to be the student object student, the Callee object is the book object, and the code function to be designed is the student learning book. We are generally accustomed to a way of thinking programming: interface-driven, can provide different flexible sub-class implementation:

//Book interface Public Interfaceibook{ Public voidlearn ();}//Booka Implementation Class Public classBooka implements IBook { Public voidLearn () {System. out. println ("Learning Booka"); }}//BOOKB Implementation Class Public classBOOKB implements IBook { Public voidLearn () {System. out. println ("Learning BOOKB"); }}

Here's a look at how the 3 method calls the book class.

1) New---Create it yourself

 Public class Student {    publicvoid  Learnbooka () {        new  Booka ();        Book.learn ();    }      Public void learnbookb () {        new  bookb ();        Book.learn ();    } }

This method needs to create a ibook object on its own when the caller student needs to call the callee ibook. The disadvantage of this approach is that the callee cannot be replaced and is responsible for the entire life cycle of the callee.
2) Get---Factory mode
All objects have their own disadvantage is that the objects created are scattered everywhere, causing administrative problems, such as the need to change a lot of code. The factory model can be used to solve this problem.

//Book Factory Public classbookfactory{ Public StaticIBook Getbooka () {IBook Book=NewBooka (); returnBook ; }     Public StaticIBook getbookb () {IBook Book=NewBOOKB (); returnBook ; }}//Student Class Public classStudent { Public voidLearnbooka () {IBook Book=Bookfactory.getbooka ();    Book.learn (); }     Public voidlearnbookb () {IBook Book=BOOKFACTORY.GETBOOKB ();    Book.learn (); }}

At this point, there is a factory class, the object creation is extracted into the factory class, the caller does not have to consider the creation of objects, just from the factory, in the modification of the callee is also no need to change too much code. However, the creation of objects is still not flexible, so that the fulfilment of the acquisition depends entirely on the factory, there is more than one intermediate process.
3) Set---external injection
Obviously, the first method relies on the Callee object, and the second relies on the factory, and there are dependencies. In order to completely solve the problem of dependency, the external injection method was adopted. The external injection is going to use the reflection mechanism of the dynamic programming in the previous chapter. Use this approach to build an IOC container. For the IOC container, it can be seen as a distillation of the factory model, which is like a big factory, and here are three types of injections

1. Interface Injection

 Public class student{    private  IBook Booka;      Public Init ()    {        = (IBook) class.forname ("booka"). newinstance ();}    }

By dynamically creating Booka instances to inject, this approach still relies on the implementation of ibook.
2. Construction Injection
A dependency is established through the constructor of the class, and the container injects its required dependencies by invoking the constructor of the class.

 Public classStudent {PrivateBooka Booka;  PublicStudent (Booka BooA) { This. Booka =Booka; }     Public voidLearn () {Booka.learn (); }} Public classFactory { Public Staticgetinstance () {Class clazz= Booka.class;//to create a class object for the Bookaclass[] param =NewClass[]{booka.class};Try{Constructor con=clazz.getconstructor (param); Booka Booka=(Booka) con.newinstance (str); Student Student1=NewStudent (Booka);}Catch(Exception e) {e.printstacktrace ();}returnStudent1; }}

This allows a student instance of the property Booka to be obtained directly through Factory.getinstance ().
3. Set Injection
The managed object conveys its own object and the value of the desired configuration through properties. Just add the setter method to the object.

 Public classStudent {PrivateBooka Booka;  PublicBooka Getbooka (Booka BooA) {returnBooka; }     Public voidSetbooka (Booka BooA) { This. Booka =Booka; }     Public voidLearn () {Booka.learn (); }} Public classFactory { Public Staticgetinstance (String fieldName) {Class clazz= Booka.class;//to create a class object for the BookaClass student = student.class; class[] param=NewClass[]{booka.class};Try{Method Method= Student.getmethod ("Set"+Change (fieldName), param); Booka Booka=(Booka) clazz.newinstance (); Booka[] Book=Newbooka[] {Booka}; Object obj=student.newinstance ();     Method.invoke (Obj,book); Student Student1=(Student) obj;Catch(Exception e) {e.printstacktrace ();}returnStudent1; }     Public Staticstring Change (String str) {string subString= Str.substring (0,1); SubString=substring.touppercase (); Str= Str.substring (1, Str.length ()); Str= SubString +str;returnstr; }}
This allowsyou to get an instance of student by simply calling Factory.getinstance ("Booka").    the advantage of dependency injection is that when you define an object in a container, the container automatically builds an instance, and the drawback is that the steps to build an object become complicated and uncomfortable and intuitive for those who are not accustomed to this approach.    Summary: From Factory mode to dependency injection, what's so complicated about it? The role of the factory model is to hit the creation of objects into the factory container, so that the modification of objects is also centralized in the container for easy maintenance. The Factory mode is not universal, so different objects need to create different methods in the container, so the use of dynamic programming technology based on reflection mechanism can solve this problem, but the process of generating objects is more and more tedious. 

Citation Links:

Factory mode, control inversion, and dependency injection

C # implements Dependency injection

Factory mode, control inversion, and dependency injection

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.