我应该使用策略模式吗,如果我有数百个动作

should I use strategy pattern, If I have hundreds of actions

我有一份 class 的翻译工作。但是它有数百种特定的翻译方法!动作代码决定了使用哪种方法!我想使用策略模式,但它会创建数百个子class!我想将方法​​命名为动作代码的结尾并使用反射来进行翻译,但我担心中止执行性能。它会被非常频繁地调用!我应该用什么设计模式或模式来解决这个问题! 代码如下:

public class Test003_Translate {

private static final String PREFIX = "translate";

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    Test003_Translate translate = new Test003_Translate();
    Map<String, String> map = new HashMap<>();
    map.put("key001", "001");
    map.put("key002", "002");
    map.put("key003", "003");
    translate.doTranslate(map, "key001");
}

private void doTranslate(Map<String, String> map, String key) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    String actionCode = map.get(key);
    Method method = Test003_Translate.class.getMethod(PREFIX + actionCode, String.class);
    String arg = "arg: ";
    Object s = method.invoke(this, arg);
}

public String translate001(String input){
    return input + "001";
}
public String translate002(String input){
    return input + "002";
}
public String translate003(String input){
    return input + "003";
}
}

您可以使用 EnumMap(比 HashMap 更小更快),如下所示:

enum Key {
    KEY_001,
    ....
}

EnumMap<Key, Runnable> enumMap = new EnumMap<>(Key.class);
enumMap.put(Key.KEY_001, YourClass::translate001);
....

和用法:

enumMap.get(someKey).run();