1.3 KiB
1.3 KiB
CSE 1105 Collaborative Software Engineering Project
Dependency Injection
Dependent-on components not managed by the component anymore, but need to be provided (injected) from outside.
Dependency Inversion Principle
Traditional Control Flow:
- App calls/uses Library
Inverted Control Flow:
- App calls interface
- the Library implements the interface
The high-level code no longer depends on the low-level code, both depend on abstractions.
For example:
public interface RailObject {
boolean isRunning();
void setDestination(String destinationName);
Duration getRunningTime();
}
public interface RailController {
private RailObject[] objects;
public RailController(RailObject[] objects) {
this.objects = objects;
}
public void setAllDestinations(StationDataSet stops) {
for (RailObject object : objects) {
// sommige dingen doen
...
}
}
}
Here, a RailObject
can be implemented by any class, as long as they provide the right interface methods, isRunning
, setDestination
, getRunningTime
. This decouples RailController
from a specific implementation of RailObject
, like Train
, such that the controller can be used for more objects.