目前,我有许多实现Processor
接口的Java类,这意味着它们都有一个processRequest(String key)
方法。想法是每个类都有一些(比如说,<10)成员Strings
,每个字符串通过processRequest
方法映射到该类中的一个方法,就像这样:
class FooProcessor implements Processor
{
String key1 = "abc";
String key2 = "def";
String key3 = "ghi";
// and so on...
String processRequest(String key)
{
String toReturn = null;
if (key1.equals(key)) toReturn = method1();
else if (key2.equals(key)) toReturn = method2();
else if (key3.equals(key)) toReturn = method3();
// and so on...
return toReturn;
}
String method1() { // do stuff }
String method2() { // do other stuff }
String method3() { // do other other stuff }
// and so on...
}
你需要一个可以在运行时访问的从键到函数的映射,你已经有了一个知道所有键的管理器,但不知道键和函数之间的映射关系。你的第一反应是使用带有 if-else 语句的映射,但是你需要一个支持一等公民函数的语言才能这样做,所以你考虑使用一个 `Map`。你也想过通过将键放入数组中并使用反射来调用方法,但你认为这可能会减慢速度。你正在寻找一种干净、开销最小的方式来将字符串映射到某种函数对象,并调用类似于 `getReturnType()` 的函数。如果需要,你可以使用第三方库,但最好避免每次执行方法查找时都要使用反射 - 也许可以使用将 `Map` 与反射相结合的缓存策略。