Interviewer: Why can Spring IOC reduce coupling?

 
  
 
  
 
  
您好,我是路人,更多优质文章见个人博客:http://itsoku.com

Some students may ask such questions when learning the Spring framework, why can the coupling between codes be reduced through dependency injection? Isn’t it okay for me to produce objects through new? Isn’t it just a line of code, one is @Resource injection, and the other is new creation. How can the coupling be reduced?

Today the blogger will take you to analyze this problem step by step

1. Create objects in the traditional way

Usually we create objects like this

WuliCar wuli = new WuliCar();
wuli.run();

The first day: Erming wanted to use a car, and then got a Wuling Rongguang through new, called the run method to start using it, and the car started running, very happy.

One month later: Erming's company has made money, and he doesn't want to drive a Wuling anymore. He wants to change to a BMW. Next, Erming will operate:

BaomaCar baoma = new BaomaCar();
baoma.run();

Very good, the car has been changed from Wuling to BMW, and it is running, very happy.

Half a year later: Erming's company has made a lot of money, Erming wants to build a helicopter, and then another operation

ZhiShenJi zhi = new ZhiShenJi();
zhi.fly();

This time the change is relatively big, BMW is replaced by helicopter, and run is replaced by fly.

Think about it first when you see this, and don’t want to look down. Is there any problem with doing this?


Thinking time is up, let's move on.

From the code, it seems that there is no big problem, so I just changed two lines of code, what's the matter. Think about it, if there are 1,000 places in your code that are written like this, wouldn’t you have to change it 1,000 times if you want to change BMW to a helicopter, and another 1,000 times to change run to fly, so don’t even think about leaving get off work at night.

2. Interface programming

After the last operation, Er Ming had to work overtime for several days to finish it. Er Ming thought about how exhausted he would be if he did this every day, no, he had to think of a way. So Er Ming thought about it, and thought about it. I have defined some methods, and everyone follows this rule, otherwise it will be fine.

public interface vehicle {
    // 定义一个交通工具接口,有一个 work 方法
 void work();
}

BMW implements this interface:

public class Baoma implements vehicle {
    @Override
    public void work() {
  System.out.println("宝马跑起来");        
    }
}

The plane implements this interface:

public class ZhiShenJi implements vehicle {
    @Override
    public void work() {
  System.out.println("直升机飞起来");        
    }
}

After the modification above, when Er Ming wants to replace the BMW with a helicopter, he only needs to modify the new part, which saves a lot of time.

3. Factory method

It is indeed better to use the interface, but the problem is still not solved. In order to improve cohesion, the full-time class is responsible for specific things, so we use a class as a factory class, which can produce both Car and ZhiShenJi

class VehicleFactory{
 VehicleFactory(){}
 public static Vehicle getInstance(String type){
  Animal result = null;
  if("car".equals(type)){
   result = new Car();
  }
  if("zhishenji".equals(type)){
   result = new ZhiShenJi();
  }
  return result;
 }
}

If ever I wanted to exercise and wanted to ride a bike, it would be easy

class VehicleFactory{
 VehicleFactory(){}
 public static Vehicle getInstance(String type){
  Animal result = null;
  if("car".equals(type)){
   result = new Car();
  }
  if("zhishenji".equals(type)){
   result = new ZhiShenJi();
  }
        if("zixingche".equals(type)){
   result = new ZiXingChe();
  }
  return result;
 }
}
Vehicle vehicle = VehicleFactory.getInstance("zixingche");
vehicle.work();

This method handed over the process of creating objects to a professional class (Factory), I just need to tell him what I need (parameters), and he will return me the correct object, just solve the problem of cohesion, But he didn't solve my declaration statement scattered in the program, I still need to replace the parameters carfromzixingche

4. Reflection

Later, Erming thought of a more brilliant idea. I don’t tell the factory what I need when I write the program, and I tell the factory what I need when it is running, and then use the reflection technology to produce it for me, isn’t it all right ? Two just do it

Vehicle vehicle = VehicleFactory.getInstance(读取配置文件);
vehicle.work();

我想要的:zixingche
zixingche.work();

You're done, so what I want is written in a configuration file, which can be created by using reflection technology, so that I don't have to do it in production, and I can just go to the configuration file to modify it when I change the car next time, and I don't need it in the code Revise.

For the production object, which is not directly related to the business, we have already extracted it to a professional factory. The professional factory still produces according to the configuration file. I only need to change one place to produce what I want, which reduces the coupling. Sexuality (the coupling between the production object and the business minimizes the impact of the production object on the business).

5. Spring IOC

Spring IOC has helped us realize the functions mentioned in the fourth point above. Spring IOC uses factory mode + reflection to realize the automatic production of objects and manage the life cycle of objects. Reduced code coupling

6. Summary

  • Dependency injection means that what you need is not created by you, but provided to you by a third party, or the container. Such a design conforms to orthogonality, which is the so-called loose coupling.

  • Dependency injection means that the caller can obtain the control of a component only by declaring a component, and the dependency management, search, and loading of the component are done externally.

  • Dependency injection means that you don't need to care about the life cycle of the object, when it is created, and when it is destroyed. You only need to use it directly. The life cycle of the object is managed by the framework that provides dependency injection.

f29502d8c77a3f5bcaa00e7a13985bf9.png

↓  Click to read the original text and go directly to my personal blog

1b468858b3bc6f9ccdcb9a2f14fca941.jpeg Are you looking

Guess you like

Origin blog.csdn.net/likun557/article/details/131733630