【发布时间】:2013-03-24 14:19:11
【问题描述】:
我有一组 API 类,它们只包含静态方法和一个私有构造函数,因此它们不能被实例化。但是,我希望第三方开发人员能够修改 API 的行为以满足他们的需求。
这是我迄今为止的解决方案(通过静态设置方法进行依赖注入)。这是开发人员将使用的公共 API 类。如您所见,它依赖于StaticApiImpl。
public class StaticApi {
private static StaticApiImpl impl = new StaticApiImpl();
private StaticApi() {}
public static void setImpl(StaticApiImpl impl) {
StaticApi.impl = impl;
}
public static void doThing() {
impl.doThing();
}
}
这是我自己编写的默认 API 实现。
public class StaticApiImpl {
public void doThing() {
System.out.println("Do thing the default way.");
}
}
这是第三方可能编写的默认实现的假设扩展版本:
public class MyCustomStaticApiImpl extends StaticApiImpl {
@Override
public void doThing() {
System.out.println("Do thing differently.");
}
}
然后,开发人员只需在插件初始化时通过 setter 方法注入他们的依赖项:
public void onLoad() throws Exception {
StaticApi.setImpl(new MyCustomStaticApiImpl());
}
我的问题是:这是正确的做法吗?是否有一些我没有听说过的专门用于此类案例的设计模式?
【问题讨论】:
-
我会完全移除 StaticApi 类,让开发者注入 StaticApiImpl 或子类的实例。
-
不,这样做的方法不正确。
标签: java design-patterns dependency-injection