Junior — Middle
Kuidas toimub sõltuvuste süstimine klassi konstruktoriga?
sobes.tech AI
Vastus AI-lt
Dependency injection through a class constructor is a way to pass necessary dependencies to an object during its creation via constructor parameters. This makes the class more modular and testable, as dependencies are explicitly passed from outside.
Example in Java:
public class Service {
private final Repository repository;
// Constructor accepts the dependency
public Service(Repository repository) {
this.repository = repository;
}
public void perform() {
repository.save();
}
}
// Usage:
Repository repo = new DatabaseRepository();
Service service = new Service(repo);
Thus, the Service class does not create or manage the Repository dependency itself, but receives it from outside, which facilitates replacing the implementation and testing.