簡體   English   中英

如何構建通用包裝器以將域對象與特定的API分離?

[英]How to build a generic wrapper to decouple domain objects from a specific API?

我正在為第三方Web服務(SOAP)api寫包裝器類。 我想以一種這樣的方式來抽象代碼與API的交互:如果業務關系發生變化,我可以刪除對第三方API的引用。 考慮以下代碼:

public Tapitype ConvertToAPIImplementation<Tapitype>(APIConverter domainToApiConverter){

  return domainToApiConverter.ConvertToAPIObject(this);

}

我想要做的是將我的函數ConvertToAPIImplementation放入一個轉換器中,該轉換器會將我的域對象轉換為我們正在使用的期望API的類型。 我應該如何實施呢?

這是一個非常簡單且常見的場景。 參考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框架,例如Unity或StructureMap。

http://unity.codeplex.com/

http://structuremap.net/structuremap/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM