mercredi 9 mars 2016

Factory Pattern with Static Factory method or Constructor

I have a hierarchy of classes RequestParams , all can be created with ExtArgs.

public interface RequestParams {
}

I also created a Factory RequestsFactory looking like this:

public class RequestFactory<P extends RequestParams> {

    private final Logger logger = LoggerFactory.getLogger(RequestFactory.class);
    final Class<P> paramsClass;

    public RequestFactory(Class<P> paramsClass) {
        this.paramsClass = paramsClass;
    }

    public Request<P> create(ExternalArgs args)  {
        P params = null;
        try {
            params = paramsClass.getDeclaredConstructor(ExternalArgs.getClass()).newInstance(args);
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            logger.error("Failed to generate request", e);
        }
        return new Request<>("get", Collections.singletonList(params));
    }

    static <P extends RequestParams> RequestFactory<P> createFactory(
            final Class<P> paramsClass) {
        return new RequestFactory<P>(paramsClass);
    }

}

where my client code is s follows:

Request devInfoRequest = RequestFactory.createFactory(RequestType.SYSTEM_INFO.getRequestClass()).create(externalArgs);

I use this ENUM in order map request types:

public enum RequestType {
    SYSTEM_INFO(DeviceInfoParams.class),
    INTERFACES(InterfacesParams.class)
}

My question is - How can use this, since I can't add neither constructor nor static builder to the RequestParams interface (or abstract class) ?

Aucun commentaire:

Enregistrer un commentaire