我使用带有异步回调的okhttp3从服务器获取JSONArrays / JSONObjects然后解析它们并创建传递给回调函数的特定对象。 对于每种方法,大多数回调代码都是相同的,但有些代码行不同。 是否有一种模式可用于减少代码行,以便我不必为不同的对象反复编写相同的代码? 我标记了每种方法不同的代码行。 我遇到的问题是在不使用switch / case和改变回调对象的情况下调用特定的JSON解析函数。
//-----------------------differs-------------------------
public void getUser(final HTTPResponseCallback<User> callback)
{
//-----------------------differs-------------------------
final String url = domain + USERS;
//-------------------------------------------------------
okHttpClient.newCall(buildRequest(url)).enqueue(new Callback()
{
Handler handler = new Handler(Looper.getMainLooper());
@Override
public void onFailure(Call call, IOException e)
{
handler.post(new Runnable()
{
@Override
public void run()
{
callback.onFailure();
}
});
}
@Override
public void onResponse(Call call, final Response response) throws IOException
{
if (response.isSuccessful())
{
try
{
String responseBody = response.body().string();
//-----------------------differs-------------------------
JSONObject jsonResponse = new JSONObject(responseBody);
final User user = JsonParser.parseUser(jsonResponse
//------------------------------------------------------
handler.post(new Runnable()
{
@Override
public void run()
{
//---------------------------------------last parameter differs----------------------------------------------
callback.onSuccess(new HTTPTransaction(response.code(), response.message(), response.header("ETag")), user);
//-----------------------------------------------------------------------------------------------------------
}
});
}
catch (JSONException e)
{
...
}
}
else
...
}
}
}
答案 0 :(得分:1)
1)使用<T>
参数化,因为类型可能不同:
public class CallBackWrapper<T> {
...
public void getUser(final HTTPResponseCallback<T> callback) { ...
2)为返回类型为T
的实例的唯一部分引入回调对象:
interface Worker {
T run(String responseBody);
}
public <T> void getUser(final HTTPResponseCallback<T> callback, Worker worker) { ...
3)调用所需的工人:
String responseBody = response.body().string();
//-----------------------differs-------------------------
final T obj = worker.run(responseBody);
//------------------------------------------------------
handler.post(new Runnable()
{
@Override
public void run()
{
//---------------------------------------last parameter differs----------------------------------------------
callback.onSuccess(new HTTPTransaction(response.code(), response.message(), response.header("ETag")), obj);
//-----------------------------------------------------------------------------------------------------------
}
});