[Interview Question] Dependency Injection
Organizing interview questions about DI
Dependency injection
Dependency: a relationship in which an object uses another object. → Dependency injection: something that establishes the relationship
Why do we need dependency injection?
public class Product {
private Apple apple;
public Product() {
this.apple = new Apple();
}
}
In this example, if a class called Product uses the Apple constructor, we are using it without injecting it. If Product is used, it can be understood as a dependency that comes with Apple. In this case, it's not a connection between objects, but a relationship between classes.
Also, if I wanted to use an additional class called Orange, I would have to make changes to the Product class constructor, which is inflexible.
In conclusion, to summarize why dependency injection is necessary
Strong coupling between classes + inflexible code
These problems can be solved with dependency injection, so I'd say it's necessary!
Application of the solution
public interface Fruit {
}
public class Apple implements Fruit {
}
public class Product {
private Fruit fruit;
public Product(Fruit fruit) {
this.fruit = fruit;
}
}
You can see that each class is guaranteed to be independent.
- adding a new Fruit doesn't change Product
- relationships between objects are formed instead of class relationships
댓글 작성
게시글에 대한 의견을 남겨 주세요.