The difference between Spring's IOC and factory patterns

IOC is the use of reflection technology to dynamically generate objects

The object generation of the factory pattern is determined in advance in the factory class

IOCs are more flexible



IoC - Inversion of Control

DI - Dependency Injection


1: How to understand IoC/DI
To understand the above two concepts, you must understand the following questions:

  • Who are the participants?
  • Dependency: Who depends on whom? Why do you need a dependency?
  • Inject: Who injects into whom? What exactly is injected?
  • Inversion of Control: Who Controls Who? Control what? Why is it called reversal (if there is reversal, there should be forward rotation)?
  • Are Dependency Injection and Inversion of Control the same concept?

Let's briefly answer the above questions, and if these questions are understood, IoC/DI will also be understood.
(1) Who are the participants:

There are generally three parties involved, one is an object; one is the container of IoC/DI; the other is an external resource of an object.
To explain the term again, an object refers to an arbitrary, ordinary Java object; the container of IoC/DI simply refers to a framework program used to implement the function of IoC/DI; the external resource of an object refers to the object Required, but obtained from outside the object, are collectively referred to as resources, such as: other objects required by the object, or file resources required by the object, and so on.


(2) Who depends on whom:

Of course, an object depends on the container of IoC/DI
(3). Why does it need to depend on:

The object needs the container of IoC/DI to provide the external resources required by the object
(4) Who injects into whom:

It is obvious that the container of IoC/DI injects an object
(5) what exactly is injected:

It is to inject external resources required by an object
(6) who controls who:

Of course, it is the container of IoC/DI to control the object
(7) what to control:

It is mainly the creation of control object instances
(8) why it is called inversion:

Reversal is relative to positive, so what is positive? Consider an application in a normal situation, if you want to use C inside A, how would you do it? Of course, it is to directly create an object of C, that is, to actively acquire the required external resource C in class A, which is called forward. So what is the reverse? That is, class A no longer actively obtains C, but passively waits, waiting for the IoC/DI container to obtain an instance of C, and then injects it into class A in reverse.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324728051&siteId=291194637