Path to Architect (39) --- IOC framework

Source: Internet
Author: User

1 Background of IOC Theory
As we all know, in a software system designed using an object-oriented method, the underlying implementation of the software system is composed of n objects, and all objects are through mutual cooperation, finally, the business logic of the system is realized.


 
Figure 1 coupling objects in the Software System


If we open the back cover of the mechanical watch, we will see a situation similar to the above, each gear drive the clockwise rotation of the hour, minute and second hands, so as to generate the correct time on the dial. This gear group is described in figure 1. It has multiple independent gears which work together to complete a task together. We can see that in this gear group, assuming a gear has a problem, it may affect the normal operation of the entire gear group.
The meshing relationship between gears in the gear group is similar to the coupling relationship between objects in the software system. Coupling between objects is inevitable and necessary, which is the basis of collaborative work. Nowadays, with the increasing scale of industrial applications, the dependency between objects is becoming more and more complex, and multiple dependencies between objects are often displayed. Therefore, architects and designers will face greater challenges in system analysis and design. A system with a high Coupling Degree between objects is bound to lead the whole body.

 

 

 
Figure 2: complex dependency between objects


The coupling relationship not only exists between objects, but also between modules of software systems and between software systems and hardware systems. How to Reduce the coupling between systems, modules, and objects is one of the goals that software projects will always pursue. To solve the problem of high coupling between objects, software expert Michael Mattson proposed the IOC theory to achieve "decoupling" between objects. Currently, this theory has been successfully applied to practice, many J2EE projects use the IOC framework spring.


2. What is IOC)
IOC is short for inversion of control. Most books translate it into "control inversion", and some others translate it into "control inversion" or "control inversion ".
In 1996, Michael Mattson first proposed the concept of IOC in an article about the object-oriented framework. We have already talked a lot about the basic idea of object-oriented design and programming. We will not repeat it here. Simply put, we will break down complicated systems into mutually cooperative objects, after these object classes are encapsulated, internal implementation is transparent to the outside, which reduces the complexity of solving this problem and can be flexibly reused and expanded. The idea put forward by IOC theory is roughly like this: decoupling between dependent objects with the help of "third parties", for example:

 


Figure 3 IOC decoupling process


As you can see, the introduction of the "third party" in the middle, that is, the IOC container, makes the four objects A, B, C, and D have no coupling relationship, the drive between gears depends on the "third party", and the control of all objects is handed over to the "third party" IOC container. Therefore, the IOC container becomes the key core of the entire system, it plays a role similar to "adhesive", and binds all objects in the system together. If this "adhesive" is not used, the objects and objects are lost, this is why some people think of IOC containers as "Adhesives.
Let's try again: remove the IOC container in the middle, and then look at the system:
 


Figure 4: system after IOC container Removal


What we see today is all the content we need to achieve the entire system. At this time, there is no coupling between the four objects A, B, C, and D, and there is no connection between them. In this case, when you implement, there is no need to consider B, C, and D at all. The dependency between objects has been minimized. Therefore, assuming that the IOC container can be implemented, what a wonderful thing for system development is that every member of development and development can only implement their own classes, it has nothing to do with others!
Let's take a look at the reason why the IOC is called? Let's take a look:
Before the IOC container is introduced to the software system, object a depends on object B, so when object A is initialized or executed to a certain point, you must create object B or use the created object B. Whether you create or use object B, you have control.
After the software system introduces the IOC container, this situation changes completely. What we see in 3 is the addition of the IOC container ?, The direct connection between object A and object B is lost. Therefore, when object A is executed to object B, the IOC container will create an object B and inject it to the place required by object.
Through the comparison, we can't see it: the process in which object A obtains dependent object B is changed from active behavior to passive behavior, and the control is reversed, this is the origin of the name "control inversion.

 

3. Alias of IOC: dependency injection (DI)
In 2004, Martin Fowler discussed the same issue. Since IOC is a reversal of control, "what aspects of control are reversed ?", After detailed analysis and demonstration, he got the answer: "the process of obtaining dependent objects is reversed ". After the control is reversed, the process of obtaining dependent objects changes from self-management to active injection by the IOC container. Therefore, he gave "control inversion" a more appropriate name called "dependency injection )". His answer is actually a method for implementing IOC: injection. The so-called dependency injection means that the IOC container dynamically injects a dependency into the object during execution.

Therefore, dependency injection (DI) and control inversion (IOC) are the same thing described from different perspectives. They refer to the method of injecting Dependencies by introducing IOC containers, decouples objects.
Let's take an example in our life to help us understand the dependency injection process. You should be familiar with USB interfaces and USB devices. USB provides great convenience for us to use computers. Many external devices now support USB interfaces.

 


Figure 6: USB interface and USB device

 

Today, we use computer hosts and USB interfaces to implement a task: reading a file from an external USB device.
When the Computer Host reads files, it does not care about what external devices are connected to the USB interface, and does not need to know. Its task is to read the USB interface. The mounted external device only needs to comply with the USB interface standard. Therefore, if I connect a USB flash disk to a computer host, the Host reads the file from the USB flash disk. If I connect an external hard disk to the computer host, then the Computer Host reads files from an external hard disk. The power of mounting an external device is determined by me, that is, the control is owned by me. As for what device is mounted to a USB interface, the Computer Host cannot decide, and it can only passively accept it. When a Computer Host requires an external device, it doesn't need to be told at all, so I will take the initiative to help it mount the external device it wants, and you can see how well my service is in place. This is a common example of dependency injection in our lives. In this process, I played the role of the IOC container.
Through this example, the idea of dependency injection is clear: when the Computer Host reads a file, I will connect the external device on which it depends. The whole process of external device injection is the same as that of injecting a dependent object into another object during system execution.
We will inject dependencies into the software system and describe the process again:
Object A depends on object B. When object A needs to use object B, the IOC container will immediately create object B and send it to object. The IOC container is an object manufacturing factory. What do you need? It will be sent to you. You can use it directly, and you no longer need to care about how your use is made, you don't have to worry about how it is destroyed. All this is done by the IOC container.
In the traditional implementation, the internal code of the program controls the relationship between components. We often use newkeyword to combine the relations between two components. Such an implementation will cause coupling between components. IOC solves this problem very well. It refers to external containers from within the program to realize the relationship between components, that is, the container dynamically injects a dependency between components into the components during the execution period.

 

4 what advantages does IOC bring to us?

Let's talk about the advantages of using a USB external device over a built-in hard disk?
1. the USB device is an external device of the Computer Host. It has nothing to do with the computer host before it is inserted into the host. The two devices are connected only after it is connected together, is correlated. Therefore, no matter what problem occurs on either side of the two, the execution of the other side will not be affected. Such a feature is reflected in the software project, that is, the maintainability is better than the license, it is easy to conduct unit testing, easy to debug programs and diagnose faults. Every class in the code can be tested separately, and each other does not affect each other. You only need to ensure that your own functions are correct. This is the advantage of low coupling or no coupling between components.
2. The independence between the USB device and the Computer Host also brings about another advantage. the manufacturer of the USB device and the manufacturer of the Computer Host can be completely unrelated to each other, the only thing they need to comply with is the USB interface standard. This feature is reflected in the software development process, but it has many advantages. Every member of the development team only needs to focus on implementing their own business logic, and does not need to care about the progress of other people's work. Because your tasks have nothing to do with others, your task can be tested separately. You do not need to depend on other components, and you do not need to clarify the responsibility. Therefore, in a large and medium-sized project, the team members have clear division of labor and clear responsibilities. It is very easy to divide a large task into small tasks, and the development efficiency and product quality will be greatly improved.
3. The same USB external device can be plugged in to any USB-enabled device, Computer Host, or DVRs. the USB external device can be reused. In a software project, this feature is highly reusable. We can separate general frequently used components and reuse them to other parts of the project or other projects, of course, this is also the basic feature of object-oriented. Obviously, IOC not only better implements this principle, but also improves the reusability of modules. All implementations that comply with the interface standards can be inserted into modules that support this standard.
Fourth, like USB external devices, the module has the hot swapping feature. The IOC generation object method is converted to the external method, that is, the object generation is defined in the configuration file, so that when we change an implementation subclass, it will become very easy, you only need to modify the configuration file, and have the hot plug-in feature.
The above advantages are not enough to impress us. Can we use the IOC framework in the project development process?

5 IOC container Technical Analysis
The most important technology in IOC is reflection programming. net C #, Java, and PhP5 are supported. In the PhP5 technical books, it is sometimes translated as "ing ". We should be very clear about the concepts and usage of reflection. In general, the object is dynamically generated based on the given class name (string method. This programming method allows an object to decide which object is generated. Reflection is widely used and has many mature frameworks, such as the Hibernate and spring frameworks in Java ,.. net. the net framework uses "reflection" as the main technical means.
Reflection technology actually appeared very early, but has been ignored and is not used further. At that time, the reflection programming method was at least 10 times slower than the normal object generation method. Today's reflection technology has been improved and optimized, and it is very mature. The speed of generating objects using reflection methods is not much different from that of the Common Object generation methods, which is about 1-2 times the speed.
We can regard the IOC container working mode as the sublimation of the factory mode and the IOC container as a factory. All the objects to be produced in this factory are defined in the configuration file, then, the reflection programming in the programming language is used to generate the corresponding object based on the class name given in the configuration file. From the implementation point of view, IOC is to generate code for the objects that were previously written in the factory method, which is defined by the configuration file, that is, to separate the factory and object generation, the purpose is to improve flexibility and maintainability.
6. Some IOC container Products
IOC containers under the sun one technical system include: lightweight spring, guice, Pico container, aveon, hivemind; heavyweight: EJB; lightweight: JBoss, jdon, and so on. Spring framework is one of the three muskeys in SSH (struts, spring, and hibernate) in Java Development. It is widely used in large and small projects and is mature and widely used, EJB is also used in key industrial projects, such as some telecom businesses.
IOC containers under the. NET technical system include spring. NET and Castle. Spring. NET is an IOC container transplanted from spring in Java, and Castle's IOC container is part of the Windsor. Both of them are lightweight frameworks that are more mature than development. Spring. net has been gradually applied to various projects.
7 What should I pay attention to when using the IOC framework?
The use of IOC framework products can bring great advantages to our development process, but we also need to fully understand the disadvantages of introducing the IOC framework, so that we can be aware of it and eliminate the abuse of the framework.
First, because the third-party IOC container is introduced in the software system, the process of generating objects becomes a little complicated. It was originally a task between the two, and there was another procedure out of thin air. Therefore, when we first started using the IOC framework, we felt that the system was not very intuitive. Therefore, a new framework will be added? Training costs for team members to learn and understand, and new training costs need to be added in the future implementation and maintenance? Users have the same knowledge system.
Second, because the IOC container generates objects through reflection, there is a certain loss in execution efficiency. If you want to pursue execution efficiency, you must weigh it.
Third, for details about IOC framework products (such as spring), a lot of preparation work is required, which is more complicated than runtime. For some small projects, it may also increase work costs objectively.
Fourth, the maturity of IOC framework products must be evaluated. If an immature IOC framework product is introduced, the entire project will be affected, so this is also a hidden risk.
We can conclude that some projects or products with low workload are not suitable for IOC framework products. In addition, assuming that the team members lack the knowledge and ability, and lack a deep understanding of IOC framework products, do not rashly introduce them. Finally, projects or products with special emphasis on execution efficiency are not suitable for introducing IOC framework products. This is the case for websites like Web2.0.

Path to Architect (39) --- IOC framework

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.