【发布时间】:2021-10-22 14:31:27
【问题描述】:
我有这个类,它包含四个私有方法,每个都有相同的两个参数,以及一个在它们之间进行选择的公共方法。 可能的方法存储在 Map 中,并且可以添加更多方法。 我想动态调用正确的方法,删除 switch..case。 有没有礼貌的方法,即没有 getMethod/invoke?
public class PlayerClass {
private MediaSource customPlayFunction1(Channel chn, OtherParam other) {
}
private MediaSource customPlayFunction2(Channel chn, OtherParam other) {
}
private MediaSource customPlayFunction3(Channel chn, OtherParam other) {
}
private MediaSource defauPlayFunction(Channel chn, OtherParam other) {
}
public void playChannel(Activity activity, Channel chn) {
//do something
switch (chn.customFunction) {
case ("CustomPlayFunction1"): {
videoSource = customPlayFunction1(chn,other);
break;
}
case ("CustomPlayFunction2"): {
videoSource = customPlayFunction2(chn,other);
break;
}
case ("CustomPlayFunction3"): {
videoSource = customPlayFunction3(chn,other);
break;
}
default: {
videoSource = defaultPlayFunction(chn,other);
break;
}
}
//do something else
}
}
【问题讨论】:
-
一种可能的方法是strategy pattern。为了实现这一点,我们可以 - 创建一个适当的接口 - 例如 -
play(...)方法 - 在单独的处理程序类中提取处理程序方法,实现接口 - 基于customFunction选择适当的处理程序类。请注意,该接口将有一些boolean handles(String customFunction)-方法来选择要选择的适当具体实现。 -
“我想动态调用正确的方法,去掉 switch..case”。您还想如何决定调用哪个方法?如果您不想使用反射,则必须有某种 if-else 或 switch-case。或者您创建一个
Map<String, BiFunction>,在其中插入key = "CustomPlayFunction1" (string), value = customPlayFunction1 (method)。这本质上只是另一种形式的开关盒。但我怀疑这会让你的代码更容易/更小/更快。