我正在开发一个使用外部API的应用程序。但我不希望我的应用程序依赖于API。因此,我一直在阅读如何实现这一目标。我读到我想要的是松耦合。我想松散地将使用外部API的类与应用程序的其余部分连接起来。我的问题是如何做到这一点。如果阅读到不同的设计模式,我就找不到一个能帮助解决问题的设计模式。
public class GoogleCalendarService
{
private const string CalendarId = ".....";
private CalendarService Authenticate(string calendarId)
{
...
}
public void Create(Booking newBooking, string userId)
{
...
InsertEvent(newEvent, userId);
}
private void Insert(Event newEvent, string userId)
{
call authenticate account
....
}
public List<Booking> GetEvents()
{
call authenticate account
...
}
}上面是我使用外部API的类的代码。在我的应用程序的其余部分中,我使用这个类的方式如下:
public class MyApplication
{
private void MyFunction()
{
GoogleCalendarService googleCalendarService = new GoogleCalendarService();
googleCalendarService.CreateEvent(..., ...)
}
}我在我的应用程序中的多个地方这样做。因此,我的问题是:如何将API类与其他类松散耦合?
编辑:我可能想要一个通用的日历服务界面,这样在需要的时候可以更容易地用其他日历服务替换google日历服务。
发布于 2018-05-27 19:06:27
这使得将google日历服务替换为其他日历服务变得更加容易。
您想要查看的主要模式是适配器。但是,您可能希望将其与依赖注入结合使用。
DI首先:
public class MyApplication
{
// constructor injection
private IGeneralCalendarService _calendarService;
public MyApplication(IGeneralCalendarService calendarService)
{
_calendarService = calendarService;
}
private void MyFunction()
{
_calendarService.CreateEvent(..., ...)
}
}适配器看起来就像
public class GoogleCalendarServiceAdapter : IGeneralCalendarService
{
// implement the interface by calliong the Google API.
}此外,您还需要用于事件等的泛型类,它们与接口属于同一层。
发布于 2018-05-27 18:51:24
您需要为该API编写一个包装器。并使用包装器IO重写该API的每个输出/输入。在此之后,您可以利用依赖注入来使用您自己的代码。通过这种方式,您可以在API周围有一个抽象层。
https://stackoverflow.com/questions/50555381
复制相似问题