Junior — Middle
How should three dependencies within a service be structured, each implementing its own interfaces and having three implementation options?
sobes.tech AI
Answer from AI
If a service has three dependencies, each implementing its own interface and having three implementation options, a good practice is to use the "Inversion of Control" (IoC) pattern and Dependency Injection.
Main recommendations:
- Define an interface for each dependency (e.g.,
ServiceA,ServiceB,ServiceC). - Create three implementations for each interface (e.g.,
ServiceAImpl1,ServiceAImpl2,ServiceAImpl3). - Use a factory or configuration to select the required implementation based on context.
- Inject dependencies via constructor or setters so that the service does not create implementations itself.
Example in Java using interfaces and constructor injection:
public interface ServiceA { void execute(); }
public class ServiceAImpl1 implements ServiceA { public void execute() { /* implementation 1 */ } }
public class ServiceAImpl2 implements ServiceA { public void execute() { /* implementation 2 */ } }
public class ServiceAImpl3 implements ServiceA { public void execute() { /* implementation 3 */ } }
public class MyService {
private final ServiceA serviceA;
private final ServiceB serviceB;
private final ServiceC serviceC;
public MyService(ServiceA serviceA, ServiceB serviceB, ServiceC serviceC) {
this.serviceA = serviceA;
this.serviceB = serviceB;
this.serviceC = serviceC;
}
// usage of dependencies
}
To select specific implementations, you can use configuration or DI frameworks (Spring, Guice) that help manage dependencies and their options.