我正在为服务器开发一个API(库)(想象一个简单的服务器接收请求并在连接上写回响应)。
我遇到的情况是我有3个不同的框架(第三方库)。所有这些都提供了一种以自己的方式处理请求的方法。想象以下是每个库的接口:
库A
public class AHandler implements AHandler {
public Response handle(Request req){
// ..
}
}
库B
public class BHandler extends SomeHandler {
public BResponse handle(BRequest req){
// ..
}
}
lib C
@Handler
public class BHandler {
@HandlerMethod
public void handle(CRequest req, CResponse res){
// ..
}
}
我想创建一个API,将handle()
方法抽象为某种统一的方法。由于A,B和C是第三方,因此我无法修改它们。
事实:
可以为所有三个库提供统一接口的API设计的最佳方法是什么?
答案 0 :(得分:1)
结合使用 facade 和 adapters ,可以达到预期的效果。
// defines the uniform interface exposed to API clients
interface Facade {
void handleRequest(Request request, Response response)
}
// defines the uniform interface each handler will have to expose
interface Adapter {
void handleRequest(Request request, Response response)
}
// takes a concrete adapter as argument and delegates to it for the concrete handle logic implementation
class ConcreteFacade implements Facade{
private Adapter adapter;
public ConcreteFacade(Adapter adapter){
this.adapter = adapter;
}
public void handleRequest(Request request, Response response){
adaper.handleRequest(request, response);
}
}
// one concrete adapter for each library
class ConcreteAdapter implements Adapter {
private AHandler handler;
public ConcreteAdapter(AHandler handler){
this.handler = handler;
}
public void handleRequest(Request request, Response response) {
//delegate to handler
}
}