我有一系列的网络服务方法调用,都遵循以下格式。每种方法的唯一区别是httpRequest.methodName()。任何人都可以想到我可以封装共同逻辑的方法吗?另请注意,我的环境是J2ME。
public Response webserviceCall(Request request) {
HTTPRequest httpRequest = new HTTPRequest(new ConnectionProperties());
String errorMessage = "";
String errorCode = "";
try {
// the only thing different
httpRequest.methodName();
} catch (SDKException e) {
errorMessage = e.getMessage();
errorCode = e.getErrorCode();
}
Error error = new Error(errorMessage,errorCode);
return new Response(error);
}
答案 0 :(得分:5)
一种替代方法是将该代码放在抽象类中,并将其更改为调用抽象方法(例如,将其命名为进程):
abstract class BaseWebService {
public abstract Response process(HTTPRequest request) throws SDKException;
public Response webserviceCall(Request request) {
HTTPRequest httpRequest = new HTTPRequest(new ConnectionProperties());
String errorMessage = "";
String errorCode = "";
try {
process(httpRequest);
} catch (SDKException e) {
errorMessage = e.getMessage();
errorCode = e.getErrorCode();
}
Error error = new Error(errorMessage,errorCode);
return new Response(error);
}
}
然后让您的每个服务扩展该类并根据需要实现process
方法
class OneService extends BaseWebService {
Response process(HTTPRequest request) throws SDKException{
return request.methodName();
}
}
对于记录,这是Template Method Pattern