mercredi 1 juin 2022

How to pass additional data to a Java Factory Object? [closed]

Consider the following Interfaces and Classes:

interface Collector {
    List<Data> collect(CollectionRequest request);
}

interface CollectorFactory {
    Collector produce(CollectionRequestType type);
}

class CollectionService {
    
    CollectorFactory collectorFactory;

    CollectionService(CollectorFactory factory) {
        this.collectorFactory = factory;
    }

    JSONObject execute(JSONObject jsonRequest) {
        CollectionRequest request = new CollectionRequest(jsonRequest);
        Collector collector = collectorFactory.produce(request.getType());
        /*
         *  TODO: some collector objects need additional object called Connection. How to pass it?
         *  This connection object is available only in this method.
         */
        List<Data> data = collector.collect(request);
        JSONObject response = new JSONObject();
        response.put("results", data);
        return response;
    }
}

I want to pass that Connection object which can be prepared only by the execute() method. One way to do that is have one more method in the factory that accepts the Connection type parameter. Is there any better way?

Aucun commentaire:

Enregistrer un commentaire