2012-07-20 106 views
2

我有一系列web服務方法調用,它們都遵循以下格式。每種方法的唯一區別是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); 
} 

回答

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); 
    } 
} 

然後,讓您的每一個服務的延伸根據需要

class OneService extends BaseWebService { 

    Response process(HTTPRequest request) throws SDKException{ 
     return request.methodName(); 
    } 
} 

對於記錄中類並實現process方法,這是Template Method Pattern