Dependency injection
In the previous chapter we briefly already discussed dependency injection (DI). Now we will dig into it a bit more detail.
Objects usually do not work on their own. Most of the time the implementation depends on the services of other classes. When we want to write something to the console we use the System
class. When we manage the table of guesses we need Color
objects and ColorManager
.
In case of writing to the console we may not realize the dependency because the class being part of the JDK class library is available all the time and all we need to do is to write System.out.println
. In this case this dependency is wired into the code. We cannot send the output somewhere else unless we change the code. This is not too flexible and in many cases we need a solution that can work with different output, different color manager or different whatever service our code depends on. The first step to do that is to have a field that has a reference of the object that gives our...