lundi 10 décembre 2018

How to force client to implement multiple generic interfaces with same type

Lets say i have some generic interfaces

public interface Service<T> {
    T getData();
}

public interface ResponseBuilder<T> {
    void build(T response);
}

and some generic class which is using those interfaces

public class Orchestrator<T> {
    private Service<T> service;
    private List<ResponseBuilder<T>> responseBuilders;

    public Orchestrator(Service<T> serviceImpl, List<ResponseBuilder<T>> buildersImpl){
        this.service = serviceImpl;
        this.responseBuilders = buildersImpl; 
    }

    public void execute() {
        T response = service.getData();
        responseBuilders
            .stream()
            .map(builder -> builder.build(response))
            .forEach(data -> storageUtil.upload(data));
    }
}

when a client developer is going to use these APIs how can i enforce him/her to pass same type in the concrete implementations of these generic interfaces, so as to avoid type mismatch exception.

An instance created of Orchestrator without specifying its type can take different types as argument eg:-

public class App{
    public static void main(String[] args){
        ResponseBuilder<String> response1 = new SomeImpl(); // type STRING
        Service<Integer> service = new SomeServiceImpl(); // type INTEGER

        // completely valid and compilable code, will throw ex at runtime
        Orchestrator orch = new Orchestrator(service, Arrays.asList(response1));
   }
}

What can be a better design?

Aucun commentaire:

Enregistrer un commentaire