与第三方库解耦的java设计模式
我正在尝试解耦第三方库的抽象类。我想公开一个新的抽象类,它将公开给用户,而不是库提供的类
我最初尝试使用适配器,但仍然在适配器类中添加第三方库的导入
我在下面添加了代码来解释我的新方法
// third party lib
abstract class ThirdParty<S> {
public abstract S doAction(S s);
}
// my goal here is to expose a different abstract class which is decoupled from third party lib
// exposed to other modules, rather than exposing the third party lib
abstract class ExposedAbstractClass<S> {
public abstract S doAction(S source);
// get hold of type using guava lib
private final TypeToken<S> typeToken = new TypeToken<S>(getClass()) { };
public Class<S> getSourceClass() { return (Class<S>) typeToken.getClass()
}
// internal class
class Builder<S> extends ThirdPartyLib<S> {
ExposedAbstractClass exposed;
public Builder(ExposedAbstractClass exposed) {
this.exposed = exposed;
}
@Override
public S doAction(S s) {
return (S) exposed.doAction(s);
}
}
//my approach breaks here when i try to invoke builder
class InvokeThirdParty {
public void invoke (ExposedAbstractClass exposed) {
Class type = exposed.getSourceClass();
Builder<type> builder = new Builder(exposed); //doesn't work since Class is runtime type, and T is compile time type
}
}
任何关于遵循哪种设计模式的指导都会非常有用
# 1 楼答案
我同意GuaravJ的回答,您可以隔离第三方依赖,并使用适配器或桥接模式从那里调用第三方库。我相信这将是一个充分的解耦解决方案
但是,您的意图似乎是remove^{cd1>},因此依赖性
或者,在
ThirdParty
类上实现反射怎么样Java与面向反射的编程兼容。这使您可以检查和检查类,并在运行时动态调用它们的方法。它将消除
ThirdParty
类的依赖项和import
语句一般来说,使用反射时,必须定位类并检查其方法。在本例中,我假设
doAction()
方法的知识来自ThirdPartyClass
一个简单的Java反射示例,遵循代码节选的思想:
不使用反射
使用反射
进一步阅读和注释