Dependency Injection
Dependency injection (DI) is a design technique in which an object receives the other objects it needs (its dependencies) from outside, usually through its constructor, instead of creating them itself. This keeps classes loosely coupled: a class depends on an interface, and the actual implementation is chosen elsewhere.
DI makes code easier to test, because real dependencies such as a database can be replaced with fakes, and easier to change. It is a form of inversion of control (IoC). Frameworks such as Spring (Java), ASP.NET Core and Angular create objects and inject their dependencies automatically.
package in.ihelpyou;
interface MessageSender {
void send(String text);
}
class EmailSender implements MessageSender {
public void send(String text) { System.out.println("Email: " + text); }
}
class OrderService {
private final MessageSender sender;
// The dependency is passed in, not created here
OrderService(MessageSender sender) { this.sender = sender; }
void placeOrder() { sender.send("Order placed"); }
}
public class Main {
public static void main(String[] args) {
new OrderService(new EmailSender()).placeOrder();
}
}