2011-11-07 30 views
0

我正在爲第三方web服務(SOAP)api編寫包裝類。我想抽象我的代碼與API的交互,以便在業務關係發生變化時刪除對第三方API的引用。請看下面的代碼:如何構建通用包裝來將域對象與特定API分離?

public Tapitype ConvertToAPIImplementation<Tapitype>(APIConverter domainToApiConverter){ 

    return domainToApiConverter.ConvertToAPIObject(this); 

} 

我想要做的是有我的函數ConvertToAPIImplementation參加一個轉換器,將我的域對象轉換成我們使用所需的類型所需的API。我應該如何實現這一點?

+0

你提供你目前正在使用和想的方法來抽象或本isalready試圖抽象? – sll

回答

1

這是一個非常簡單和常見的情況。參考GoF模式適配器,抽象工廠和代理。

[編輯:添加更多的代碼來幫助說明解決方案]

您需要定義自己的API(或抽象接口)表示,任何第三方API需要提供給您的應用程序的功能。

IPancakeMaker 
{ 
    Pancake MakePancake(decimal radius); 
} 

然後編寫實現該接口,並取決於您當前的第三方API提供者...

WalmartPancakeMaker : IPancakeMaker 
{ 

    Walmart3rdPartyAPI _w3paPancakeMaker = new Walmart3rdPartyAPI(string apiKey); 

    // ... set 3rd party settings, defaults, etc 

    // Implement IPancakeMaker 
    public Pancake MakePankcake(decimal radius) 
    { 
     Walmart3rdPartyPancakeEntity thirdPartyPancake = _w3paPancakeMaker.BakeMeACakeJustAsFastAsYouCan(radius); 

     return this.ConvertToPancakeInMyDomain(thirdPartyPancake); 
    } 
} 

創建服務類(或一些其他業務流程),以控制與您的供應商互動,使用依賴注入,以避免緊密耦合的提供商...

public class MakePancakesService 
{ 
    IPancakeMaker _pancakeMaker = null; 

    // Constructor takes the concrete Provider of IPancakeMaker 
    // Your calling code is not aware of the actual underlying API 
    public MakePancakesService(IPancakeMaker pancakeMaker) 
    { 
     _pancakeMaker = pancakeMaker; 
    } 
} 

使用流行的DI框架,如統一或StructureMap。

http://unity.codeplex.com/

http://structuremap.net/structuremap/

相關問題