2009-04-09 115 views
3

我參與了幾個與Facebook和Netflix等外部服務連接的項目。在這個時候,我用來訪問這些API的大多數庫(包括我自己編寫的API)都有單一的方法,所以調用特定的API函數,但似乎總是調用某種基本方法來發出請求。事情是這樣的:最佳外部REST API訪問模式?

public class ExternalApi 
{ 
    public string SendMessage(criteria) 
    { 
     //do something unique to this method with criteria like 
     //like generating an xml statement or fql query 

     return SendRestRequest(modifiedCriteria); 
    } 

    public string GetData(criteria) 
    { 
     //do something unique to this method with criteria like 
     //like generating an xml statement or fql query 

     return SendRestRequest(modifiedCriteria); 
    } 

    public string SendRestRequest(modifiedCriteria) 
    { 
     //add global things to modifiedCriteria like authentication bits 
     //or wrapping the criteria in some xml or json shell 

     var request = new HttpRequest(); 
     //make the request, return data 
    } 
} 

所以我的問題是有沒有更好的模式或OO主要用在這裏所以每個奇異的API調用方法我沒有顯式調用每次基本方法是什麼?

就是我正在尋找某種調用攔截模式,如ASP.NET MVC框架和ActionResults?

編輯1:我不希望使用任何其他服務或圖書館一樣WCF的功能。對於這些項目,我只使用這些API的1-5%的功能,並且傾向於爲自己的代碼推出這些東西。

回答

0

我必須爲我的學位課程中的一個課程安排一個REST客戶端。我去一個分層的方法,並試圖門面模式應用到抽象的細節

interface HTTPRequest{ 
    public void get(); 
    public void post(); 
    public void put(); 
    public void delete(); 
} 

的HTTPRequest提供基本的HTTP功能,然後,我創建RESTClient實現

interface RestClient{ 
    public void create(); 
    public void read(); 
    public void update(); 
    public void delete(); 
} 

這給了我一樣的界面,更CRUD 。然後我做的是構建一個基本的RestClient類,它可以被子類化以添加自定義功能。每個函數都有一個相應的回調函數,它在將數據返回給調用者之前調用它。這被命名爲「createResultProcessor」,這可能會寫在RestClient的子類中,以提供自定義結果解析等。

從來沒有想過我會這麼說,因爲我已經制作了足夠多的UML圖,但是因此真的可以使用一些UML圖設施!