简体   繁体   English

从第三方库解耦

[英]Decoupling from 3rd party library

I am using a third party HTTP client to make GET, POST calls. 我正在使用第三方HTTP客户端进行GET,POST调用。 I don't want to tie my code to this library. 我不想将我的代码绑定到该库。 So I've decided to create an interface called HttpClient and an implementation of it called HttpClientImpl. 因此,我决定创建一个名为HttpClient的接口和一个名为HttpClientImpl的实现。

One of the methods in the interface is: 界面中的方法之一是:

Response get(String url);

The Response object being returned from the interface is the object from the third party library. 从接口返回的Response对象是第三方库中的对象。 So this technically does not decouple my code from the third party library. 因此,从技术上讲,这不会使我的代码与第三方库脱钩。

What is the best approach to decouple myself? 解耦自我的最佳方法是什么? Should I create my own response object that can wrap the response of the third party library? 我应该创建自己的响应对象来包装第三方库的响应吗?

This is a classic case of the Mediator design pattern: The class which uses the HTTP client shouldn't be exposed to neither the HTTP client implementation (which you've already encapsulated) nor its response object. 这是介体设计模式的经典案例:使用HTTP客户端的类既不应该暴露给HTTP客户端实现(您已经封装了),也不应该暴露给它的响应对象。

Using generics here will not prevent the using class from knowing the response class in this case. 在这种情况下,在此处使用泛型将不会阻止using类知道响应类。

As you suggested - have a wrapping response class / have a converter from the 3rd party response to one of your own. 如您所建议-具有包装响应类/从第3方响应转换为您自己的响应方。

Instead of abstracting the http library, have you considered abstracting the repositories you are accessing through Http? 您是否考虑过抽象通过Http访问的存储库,而不是抽象http库? Say for example, you have the restful endpoints for Tweets: 举例来说,您拥有Tweets的宁静端点:

GET    https://someapi.com/Tweets
GET    https://someapi.com/Tweets/{id}
POST   https://someapi.com/Tweets
PUT    https://someapi.com/Tweets/{id}
DELETE https://someapi.com/Tweets/{id}

It would make sense to have a TweetRepository class, which can create, read, update and delete tweets. 拥有一个TweetRepository类是TweetRepository该类可以创建,读取,更新和删除tweet。 The interface for this class might look something like the following: 此类的接口可能类似于以下内容:

public interface TweetRepository {
    public List<Tweet> get();
    public int add(Tweet tweet);
    public void remove(int id);
    public Tweet get(int id);
    public void update(int id, Tweet tweet);
}

If your controllers use the interface, then you can make your implementation use whatever http library you want without introducing coupling. 如果您的控制器使用该接口,那么您可以使实现使用您想要的任何http库,而无需引入耦合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM