We creates a dependency between the Client
and the ExamplieService
. We are instantiating ExamplieService
every time we call Client()
, which means the Client
class directly depends on the ExamplieService
class.
public class Client {
private ExampleService service;
Client() {
service = new ExampleService();
}
}
We create an abstraction by having the ExamplieService
dependency class in Client
’s constructor signature (not initializing dependency in class).
Constructor injection allows injecting values to immutable fields and makes testing easier.
public class Client {
private ExampleService service;
Client(Service service) {
this.service = service;
}
}
This allows us to call the dependency then pass it to the Client
class like so:
ExampleService service = new ExampleService(); // dependency
Client client = new Client(service);
public void setService(Service service) {
this.service = service;
}
public interface ServiceSetter {
public void setService(Service service);
}
public class Client implements ServiceSetter {
private Service service;
@Override
public void setService(Service service) {
this.service = service;
}
}