【发布时间】:2018-11-03 15:59:47
【问题描述】:
我有 2 个(或更多)存储相同内容的数据源;我想编写一个接口,其中包含在其中查找项目的方法。示例:
public interface CarFinder {
public Car findById(String id);
}
然后我可以写一个这样的类并使用它:
public class CustomCarFinder implements CarFinder {
public Car findById(String id) {
...
return someCar;
}
}
...
Car aCar = customCarFinder.findById("1");
CustomCarFinder 知道如何连接到数据源并为我检索Car。
问题是,对于我的第一个数据源,CustomCarFinder 每次我调用“findById”时都可以连接到它;对于第二个数据源,知道如何获取连接的是CarFinder 的客户端,而不是CarFinder。为了向CarFinder 提供连接信息,我写了如下内容:
public interface CarFinder {
public Car findById(String id, Object... context);
}
public class CustomCarFinder implements CarFinder {
public Car findById(String id, Object... context) {
//The Varargs (context) are not used in this version
...
return someCar;
}
}
public class AnotherCustomCarFinder implements CarFinder {
public Car findById(String id, Object... context) {
//Extract the connection here from the Varargs
CustomConnection connection = (CustomConnection)context[0];
...
//Somehow I find the car via this CustomConnection thing
return someCar;
}
}
...
Car aCar = customCarFinder.findById("1");
Car anotherCar = anotherCustomCarFinder.findById("1", aCustomConnection);
您看到我使用了可变参数,以便我可以使用 API 的任一版本或版本。在不需要提供连接的第一种情况下,我仍然可以使用:
Car aCar = customCarFinder.findById("1");
如果我需要提供连接,那么:
Car anotherCar = anotherCustomCarFinder.findById("1", aCustomConnection);
Finder 类是作为 Spring 单例实现的,因此它们是共享的,因此为了避免线程问题,它们是无状态的,所以我不想在使用这些方法之前设置“连接”;这就是为什么我将连接作为可变参数传递。
还有其他方法可以做同样的事情吗?
在使用 Varargs 时,我收到了(来自同事的)反对意见,我应该用不同类型的 Connection 类型重载“findById”方法。
我反对这一点,因为我不希望界面反映我正在连接的数据源的类型。如果可能的话,我希望界面保留:
public Car findById(String id);
我也不喜欢 Varargs,但我不知道如何摆脱它们并仍然完成我想要的。
【问题讨论】:
-
有什么理由不能将自定义连接作为查找器的属性?
-
Joe,我刚刚更新了提到这一点的问题:“Finder 类作为 Spring 单例实现,因此它们是共享的,因此为了避免线程问题,它们是无状态的,所以我不想设置使用方法之前的“连接”;这就是我将连接作为可变参数传递的原因。”
标签: java design-patterns variadic-functions overloading generic-programming