What is Inversion of Control?

2020-01-22 11:28发布

Inversion of Control (IoC) can be quite confusing when it is first encountered.

  1. What is it?
  2. Which problem does it solve?
  3. When is it appropriate to use and when not?

30条回答
来,给爷笑一个
2楼-- · 2020-01-22 12:06

Programming speaking

IoC in easy terms: It's the use of Interface as a way of specific something (such a field or a parameter) as a wildcard that can be used by some classes. It allows the re-usability of the code.

For example, let's say that we have two classes : Dog and Cat. Both shares the same qualities/states: age, size, weight. So instead of creating a class of service called DogService and CatService, I can create a single one called AnimalService that allows to use Dog and Cat only if they use the interface IAnimal.

However, pragmatically speaking, it has some backwards.

a) Most of the developers don't know how to use it. For example, I can create a class called Customer and I can create automatically (using the tools of the IDE) an interface called ICustomer. So, it's not rare to find a folder filled with classes and interfaces, no matter if the interfaces will be reused or not. It's called BLOATED. Some people could argue that "may be in the future we could use it". :-|

b) It has some limitings. For example, let's talk about the case of Dog and Cat and I want to add a new service (functionality) only for dogs. Let's say that I want to calculate the number of days that I need to train a dog (trainDays()), for cat it's useless, cats can't be trained (I'm joking).

b.1) If I add trainDays() to the Service AnimalService then it also works with cats and it's not valid at all.

b.2) I can add a condition in trainDays() where it evaluates which class is used. But it will break completely the IoC.

b.3) I can create a new class of service called DogService just for the new functionality. But, it will increase the maintainability of the code because we will have two classes of service (with similar functionality) for Dog and it's bad.

查看更多
爷的心禁止访问
3楼-- · 2020-01-22 12:07

It seems that the most confusing thing about "IoC" the acronym and the name for which it stands is that it's too glamorous of a name - almost a noise name.

Do we really need a name by which to describe the difference between procedural and event driven programming? OK, if we need to, but do we need to pick a brand new "bigger than life" name that confuses more than it solves?

查看更多
虎瘦雄心在
4楼-- · 2020-01-22 12:08

Inversion of Controls is about separating concerns.

Without IoC: You have a laptop computer and you accidentally break the screen. And darn, you find the same model laptop screen is nowhere in the market. So you're stuck.

With IoC: You have a desktop computer and you accidentally break the screen. You find you can just grab almost any desktop monitor from the market, and it works well with your desktop.

Your desktop successfully implements IoC in this case. It accepts a variety type of monitors, while the laptop does not, it needs a specific screen to get fixed.

查看更多
做个烂人
5楼-- · 2020-01-22 12:08

Let to say that we make some meeting in some hotel.

Many people, many carafes of water, many plastic cups.

When somebody want to drink, she fill cup, drink and throw cup on the floor.

After hour or something we have a floor covered of plastic cups and water.

Let invert control.

The same meeting in the same place, but instead of plastic cups we have a waiter with one glass cup (Singleton)

and she all of time offers to guests drinking.

When somebody want to drink, she get from waiter glass, drink and return it back to waiter.

Leaving aside the question of the hygienic, last form of drinking process control is much more effective and economic.

And this is exactly what the Spring (another IoC container, for example: Guice) does. Instead of let to application create what it need using new keyword (taking plastic cup), Spring IoC container all of time offer to application the same instance (singleton) of needed object(glass of water).

Think about yourself as organizer of such meeting. You need the way to message to hotel administration that

meeting members will need glass of water but not piece of cake.

Example:-

public class MeetingMember {

    private GlassOfWater glassOfWater;

    ...

    public void setGlassOfWater(GlassOfWater glassOfWater){
        this.glassOfWater = glassOfWater;
    }
    //your glassOfWater object initialized and ready to use...
    //spring IoC  called setGlassOfWater method itself in order to
    //offer to meetingMember glassOfWater instance

}

Useful links:-

查看更多
兄弟一词,经得起流年.
6楼-- · 2020-01-22 12:08

I've read a lot of answers for this but if someone is still confused and needs a plus ultra "laymans term" to explain IoC here is my take:

Imagine a parent and child talking to each other.

Without IoC:

*Parent: You can only speak when I ask you questions and you can only act when I give you permission.

Parent: This means, you can't ask me if you can eat, play, go to the bathroom or even sleep if I don't ask you.

Parent: Do you want to eat?

Child: No.

Parent: Okay, I'll be back. Wait for me.

Child: (Wants to play but since there's no question from the parent, the child can't do anything).

After 1 hour...

Parent: I'm back. Do you want to play?

Child: Yes.

Parent: Permission granted.

Child: (finally is able to play).

This simple scenario explains the control is centered to the parent. The child's freedom is restricted and highly depends on the parent's question. The child can ONLY speak when asked to speak, and can ONLY act when granted permission.

With IoC:

The child has now the ability to ask questions and the parent can respond with answers and permissions. Simply means the control is inverted! The child is now free to ask questions anytime and though there is still dependency with the parent regarding permissions, he is not dependent in the means of speaking/asking questions.

In a technological way of explaining, this is very similar to console/shell/cmd vs GUI interaction. (Which is answer of Mark Harrison above no.2 top answer). In console, you are dependent on the what is being asked/displayed to you and you can't jump to other menus and features without answering it's question first; following a strict sequential flow. (programmatically this is like a method/function loop). However with GUI, the menus and features are laid out and the user can select whatever it needs thus having more control and being less restricted. (programmatically, menus have callback when selected and an action takes place).

查看更多
▲ chillily
7楼-- · 2020-01-22 12:09

For example, task#1 is to create object. Without IOC concept, task#1 is supposed to be done by Programmer.But With IOC concept, task#1 would be done by container.

In short Control gets inverted from Programmer to container. So, it is called as inversion of control.

I found one good example here.

查看更多
登录 后发表回答