2016-04-14 52 views
11

我是新來改造,並想知道什麼是最佳做法。我應該使用單身改造嗎?

下面是一些抽象的代碼,我在網上找到:

public class RestClient 

{ 
    private static final String BASE_URL = "your base url"; 
    private ApiService apiService; 

    public RestClient() 
    { 
     Gson gson = new GsonBuilder() 
       .registerTypeAdapterFactory(new ItemTypeAdapterFactory()) // This is the important line ;) 
       .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'") 
       .create(); 

     RestAdapter restAdapter = new RestAdapter.Builder() 
       .setLogLevel(RestAdapter.LogLevel.FULL) 
       .setEndpoint(BASE_URL) 
       .setConverter(new GsonConverter(gson)) 
       .setRequestInterceptor(new SessionRequestInterceptor()) 
       .build(); 

     apiService = restAdapter.create(ApiService.class); 
    } 

    public ApiService getApiService() 
    { 
     return apiService; 
    } 
} 

,並讓說,我想打一個API請求/這個函數調用

RestClient restClient = new RestClient(); 
restClient.getApiService().getPosts(); 

我的問題是我應該做新的restClient對象或這應該是一個單身人士,或者ApiService應該是一個單身人士。

最佳做法是什麼?請記住,我不想使用依賴注入,我只是想了解如何最好地使用改造。

你們會怎麼做這個電話?

回答

3

您擁有的代碼很好。您可以將restClient作爲單例保留,然後只要再次獲取帖子(每次不要創建新的restClient),只需撥打restClient.getApiService().getPosts();即可。

+1

如果是單身人士,它可以並行處理兩個或多個API請求嗎? – user1796624

+3

是的,它可以處理很多並行請求 - 我不知道限制是什麼,但是當超過這個限制時,它會對請求進行排隊(假設你正在異步使用它,你應該這麼做)。 我已經成功地在其中連續快速拋出了一打以上的異步請求,而不必擔心有多少未完成的請求。 – GreyBeardedGeek

7

你應該以任何你喜歡的方式(枚舉,標準getInstance()或甚至double check)以單身作爲RestClient

將它們保持爲單例會提高性能,因爲您不會創建每次成本高昂的對象,如Gson,RestAdapterApiService

編輯: 可以通過改進同時處理的最大請求取決於HttpClient配置。

OkHttp一起使用時,默認值爲64(它在Dispatcher中定義)。

然而,它可以通過setMaxRequests()操縱,請記住不會產生太多的線程(它可能會導致OutOfMemory)。