首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >松耦合类

松耦合类
EN

Stack Overflow用户
提问于 2018-05-27 18:44:14
回答 2查看 74关注 0票数 1

我正在开发一个使用外部API的应用程序。但我不希望我的应用程序依赖于API。因此,我一直在阅读如何实现这一目标。我读到我想要的是松耦合。我想松散地将使用外部API的类与应用程序的其余部分连接起来。我的问题是如何做到这一点。如果阅读到不同的设计模式,我就找不到一个能帮助解决问题的设计模式。

代码语言:javascript
复制
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的类的代码。在我的应用程序的其余部分中,我使用这个类的方式如下:

代码语言:javascript
复制
public class MyApplication
{
   private void MyFunction()
   {
       GoogleCalendarService googleCalendarService = new GoogleCalendarService();

       googleCalendarService.CreateEvent(..., ...)
   }
}

我在我的应用程序中的多个地方这样做。因此,我的问题是:如何将API类与其他类松散耦合?

编辑:我可能想要一个通用的日历服务界面,这样在需要的时候可以更容易地用其他日历服务替换google日历服务。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-27 19:06:27

这使得将google日历服务替换为其他日历服务变得更加容易。

您想要查看的主要模式是适配器。但是,您可能希望将其与依赖注入结合使用。

DI首先:

代码语言:javascript
复制
public class MyApplication
{
   // constructor injection
   private IGeneralCalendarService  _calendarService;
   public MyApplication(IGeneralCalendarService  calendarService)
   {
     _calendarService = calendarService;  
   }

   private void MyFunction()
   {
       _calendarService.CreateEvent(..., ...)
   }
}

适配器看起来就像

代码语言:javascript
复制
public class GoogleCalendarServiceAdapter : IGeneralCalendarService  
{
   // implement the interface by calliong the Google API.
}

此外,您还需要用于事件等的泛型类,它们与接口属于同一层。

票数 3
EN

Stack Overflow用户

发布于 2018-05-27 18:51:24

您需要为该API编写一个包装器。并使用包装器IO重写该API的每个输出/输入。在此之后,您可以利用依赖注入来使用您自己的代码。通过这种方式,您可以在API周围有一个抽象层。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50555381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档