Search code examples
javadesign-patterns

Best pattern to read a configuration object


I need to map a configuration file into an object Configuration (this is already done) which is a composition of several configuration objects, each one used by a service. For instance, the Configuration class is composed by ConfA and ConfB classes:

public class Configuration {

    private ConfA confA;
    private ConfB confB;

    //getters and setters
}

Then we have an interface Service implemented by classes ServiceA and ServiceB, each one uses ConfA and ConfB respectively:

public interface Service {

    void work(Configuration configuration);
}

With my current approach, in each particular service I have to do something like this to obtain the proper configuration:

public class ServiceB implements Service {

    @Override
    public void work(Configuration configuration) {
        ConfB confB = configuration.getConfB();
    }
}

Is there any pattern to avoid this code repetition ConfB confB = configuration.getConfB(); in each service? Any way to avoid the service to know how to retrieve their own configuration?


Solution

  • I reckon that you can do simpler:

    public class ServiceB implements Service {
    
        @Override
        public void work(ConfB bConf) {
            ConfB confB = bConf;
        }
    }
    

    So high level module will inject ConfB into lower level module ServiceB.