listboss
listboss

Reputation: 886

Instantiating child (concrete) classes of a generic abstract class whose constructor needs other parametric class

A library I'm trying to use has a generic abstract class with two children classes that implement the base. I want to write a class that will automatically create an instance of one of the children based on parametric type of constructor's argument.

Snippets

public abstract class JsonRequest<T> {
    public JsonRequest(String body, Listener<T> listener) {}
}
public class JsonArrayRequest extends JsonRequest<JSONArray> {
    public JsonArrayRequest(JSONArray body, Listener<JSONArray>) {}
}
public class JsonObjectRequest extends JsonRequest<JSONObject> {
    public JsonObjectRequest(JSONObject body, Listener<JSONObject>) {}
}

Now I want to wrap the two concrete children so that the wrapper/factory would automatically decide which one to call/instantiate based on class of parametric type, something like this (and I get all sort of compiler errors)

public class RequestFactory<T> {
    private Listener<T> mListener;

    public RequestFactory(T body, Listener<T> lis) {
        mListener = lis;
        if (body instanceof JSONArray) {
            // Call JsonArrayRequest constructor
            JsonArrayRequest(body, mListener);
        }
        else if (body instanceof JSONObject) {
            // Call JsonObjectRequest constructor
            JsonObjectRequest(body, mListener);
        }
    }
}

(I'm actually trying to use Android's Volley library)

Upvotes: 0

Views: 1055

Answers (1)

Tanmay Patil
Tanmay Patil

Reputation: 7057

You are looking for Abstract Factory Design Pattern

public interface RequestFactory<T> {
    public JsonRequest<T> create(T body, Listener<T> listener);
}

public class ArrayRequestFactory implements RequestFactory<JSONArray> {
    @Override
    public JsonArrayRequest create(JSONArray body, Listener<JSONArray> listener) {
        return new JsonArrayRequest(body, listener);
    }
}

public class ObjectRequestFactory implements RequestFactory<JSONObject> {
    @Override
    public JsonObjectRequest create(JSONObject body, Listener<JSONObject> listener) {
        return new JsonObjectRequest(body, listener);
    }
}

The constructor is selected through dynamic dispatch in stead of if conditions.

Upvotes: 1

Related Questions