How to understand IOC (inversion of Control)?

Source: Internet
Author: User
RT, how to understand IOC (inversion of Control)? If you can write a demo to explain the best.

Reply content:

RT, how to understand IOC (inversion of Control)? If you can write a demo to explain the best.

I tried to search, the Chinese material basically put the IOC (Control Flip) and Di (dependency injection) confused, even stackoverflow on the first answer also made the same problem (fortunately, there are high votes against the comments, otherwise my world view is going to break down)

Control rollover is a pattern of code reuse (note not design mode)

General (non-IOC) reuse, usually a user code invocation component (any form of reused code, collectively referred to as a component in this answer). That is, the user code solves "Why is it works, what does", the component solves "How to Do", the logical entrance is the user code,

The control rollover is a component that invokes the user code, which is the component that solves "why it works, when does," and the user code solves "what does", and the logical entry is the component

The following is an example of a control rollover other than di

    • Interface/virtual function component Call interface/virtual function, specifically implemented by user code
    • Publish Subscription (event) mode component trigger event, user code subscription event
    • Callback user code write callback, component to invoke
    • almost anything that can be called a framework user code implements specific business logic where it is defined, and the rest of the framework is responsible for

Don ' t call me, I'll call you

Normal process

You went to the library to borrow books, but not.

So you went home.

Then you go to the library every day to see if your book has arrived.

If not, then you go home, continue to wait ...

The next day, go and see, ...

All the time until we got the book.

Ioc

You went to the library to borrow books, but not.

So you registered and went home.

Back home, brush the micro-bo, brush SF, the code of the masturbate.

When the book is over, the administrator informs you.

You go get the book.

Don ' t call me, I'll call you

The IOC is to let the framework create something for us.

App::bind('sms', function () {   // Create a new SMS component.   $sms = new SMSClient;   $sms->setUsername('shauna');   $sms->setPassword('1_5t341_c4t5!');   // Return the created SMS component.   return $sms;});

According to the Clouser function feature, the code above does not create $sms objects.
$app->make (' SMS '), $sms object is created. The so-called reversal is probably created on demand. When it is used, the creation is triggered, not created.

Because the programmer itself is a kind of peasant workers, but also want to install some of the tall, for self-appreciation, so created this very NB terminology, pretending to be an atomic bomb. Don't care too much.

The essence is oriented to abstract programming, the IOC describes the characteristics, the concrete implementation of Di description, the two have a common place. It can be understood that: using DI to achieve an IOC-specific framework, the ultimate embodiment of the concept of abstract programming, enhance the system's scalability.
The common "polymorphic" is for abstract programming, such as:

Person person = new Male();person.say();person.run();person.eat();

Now to designate person as female, you can simply replace the first line:

Person person = new Female();

There are few changes, but you can still do it a bit more thoroughly: could you do it without changing the existing code? The answer is "DI".
Apart from spring, we can also fully implement a set of the most streamlined similar functions:

Person person = SpringLike.getBeanFromConfig('person');

This line of code means that an instance of person is generated from a configuration file, such as:

person=com.xx.Male

Specific principles do not repeat, we are familiar with.
To get back to the question above, now to switch the feature to female, just change the configuration file:

person=com.xx.Female

Further transfer of control to the configuration file, so that the modification does not involve business logic code.
As you can see, "DI" uses polymorphism in a more thorough way and goes further in the context of abstract programming. "IOC" is a feature that is embodied in abstract programming and does not conflict with "DI" itself.

In layman's words, an item is made up of various classes. A class can be used in many places in a project.

If the traditional way of writing is that every place needsnew Class()
If the parameters are complex, every place needsnew Class(param1, param2, param3, ..)
Each time you modify the constructor of the class, each place needs to be modified. Large workload and high coupling degree.

But you can initialize the class you want to use, put it in a container, save it, and the other places you need to use it.
The only way to call the containerContainer->getClassINeed()
So, using this class and generating this class is separated by the middle container.
Examples can be seen in Phalcon the framework, the examples given in the document, to teach you to build your own container

Some of the design patterns generated by the management object are itself a container implementation, such as common factory patterns

For example, one day, you go to Qingfeng bun shop to eat steamed buns, after the door you need to find the first point of the table where, and then tell the waiter what you want, and then go to the mouth to lead the steamed bun. This is your main process, everything is under your control, but if you do not take the initiative, there is no steamed buns to eat.

The next day, you go to another big bun shop to eat buns, here, you just sit down and say I want to eat steamed buns, there will be a waiter for you to bring the buns. This is a restaurant-based process, you do not need to know where to eat, where to pick up buns.

If the first process is "positive", then the second process is "reverse". This is called the IOC. However, the name is not easy to understand, because the concept of positive and reverse is relative, you can also say that the second process is positive.

Applying this concept to GUI programming is the difference between sequential execution and event handling. You wrote it yourself. Programs are executed sequentially, such as entering a user name in the first step, entering a password in the second, and then performing a login operation. With Windows or other graphical interface frameworks, it is up to the framework to run your program and notify your program after the user has entered the content, and you do the processing. Event-driven is a representation of the IOC in relation to sequential execution.

Apply this concept to dependency management, assuming that your program needs to refer to another object, you need to create this object in your code, and after applying IOC mode, your program is no longer actively creating third-party objects, but running in a container or frame, such as spring, Then wait for spring to pass in the object you need to create. This is another form of representation of the IOC, which is dependency injection (DI).

As few words was not clear, I wrote an article here, http://segmentfault.com/blog/zhaoyi/1190000002411255

It is recommended to look at the principle of the spring framework, which relies on registration

The normal way of writing, is the upper layer called the bottom package good method, from the bottom to provide interface, so-called control inversion refers to the underlying execution logic can be determined by the upper layer, write what, the bottom of what to do, its advantage is flexible, easy to expand, like @bigxu write code.

Think about it, the program you're writing is manipulating something, say, moving some numbers, but how do you show that your program starts manipulating the image it's trying to manipulate? Then you have to write some programs to make a point (with) your program, you define a rule, or follow a set of rules, so that people can manipulate themselves, which is actually control the reverse, that is, you want to give control to someone else, think about it, the fact that this kind of anti-rotation is everywhere, more importantly, How do you let someone else adjust your program? Requires an interface, so the IOC also guides you to consider programming problems from an interface-oriented

IoC, control reversal, give control of XX to others.
Spring's di is where you give the work of the new object to spring.

Reference Spring IOC container
Recommended Articles for reading
Inversion of Control Containers and the Dependency injection pattern
Inversionofcontrol
Write yourself an IOC tool

IOC popular point that you think of him as a big factory, you ask him what object, he gives you what object, it is so simple
He is like a global variable that can be accessed in every object
You ask him what he wants object, he gives you something.

The main role of IOC is to parse the class instance, why parse? Instead of getting it directly? Because the class has dependencies on other classes. The IOC container can parse all the dependencies of a multilayer level.

If you are looking at the Laravel frame, you can look at: Service Container (IOC container)

Dependency injection and control reversal are all to achieve the same decoupling effect, the IOC is not straightforward enough, so the industry said that a wide range of discussions, the final software industry, the leading figure Martin Fowler proposed di concept to replace the IOC, That is, the invocation class's dependency 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.

Dependency injection is a way of implementing control inversion.

  • 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.