我想将api与实现分离,让实现模块依赖于api模块,但是我遇到了api实际上依赖于实现的问题,不知道如何进行。
Api/Builder.java
public interface Builder{
static Builder create(version) {
if (version < N)
return new subBuilder1()
else
return new subBuilder2()
}
}
Impl/subBuilder1.java
public static class subBuilder1 implements Builder{
public subBuilder1() {......}
......
}
Impl/subBuilder2.java
public static class subBuilder2 implements Builder{
public subBuilder2() {......}
......
}
Builder 是一个接口,我想将其移至 api 模块中。
subBuilder1和subBuilder2是实际实现,它们目前位于实现模块中。
由于当前实现模块依赖于api模块,因此我无法将interface Builder移动到api模块中,因为Builder实际上依赖于subBuilder1和subBuilder2。
如何解决API调用实现的问题?依赖注入适用于这种情况吗?
您正在寻找 SPI 吗?
可以考虑在API模块中定义一个工厂接口,然后在impl模块中实现这个工厂接口,并为SPI添加相应的配置文件。
// api
public interface Builder {
static Builder create(version) {
ServiceLoader<BuilderFactory> bfs = ServiceLoader.load(BuilderFactory.class);
Iterator<BuilderFactory> itr = bfs.iterator();
if (itr.hasNext()) {
BuilderFactory bf = itr.next();
return bf.create(version);
}
throw new IllegalStateException();
}
}
public interface BuilderFactory {
Builder create(version);
}
// impl
// create [META-INF/services/BuilderFactory's Full classname] in impl module and
// write "DefaultBuilderFactory's full classname"
public class DefaultBuilderFactory implements BuilderFactory {
Builder create(version) {
if (xx) {
return new Builder1;
}
return new Builder2;
}
}