我正在尝试重构下一个案例:
class Gen{
public void startClick(A a, B b, List<C> lstC, SortX sort){
for (int i=0; i<lstC.size(); i++){
try{
// some code with try and catch statement
switch (sort){
case SortA:
newOne(a, b, lstc);
break;
case SortB:
otherfunction(a);
break;
case SortC:
someotherfunction(lstC, a);
break;
}
}
} catch (Exception e){ //some code}
}
}
我尝试创建一个对象并将其放入 case 中,就像我们在这里看到的那样:http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
所以我创建了一个对象:SortOfType
,然后我还为每种情况创建了一个对象(SortA
、SortB
、排序 C
)。 SortOfType
中的函数获取 Gen
的实例,其他 Sort 对象也是如此。我没有成功的是调用 Gen 类的 sortOfType。我该怎么做?这种重构在这里是可能的吗?
最佳答案
你定义一个接口(interface),当需要一个 Action 时调用它
public interface SortX {
public void startClick(A a, B b, C c);
}
public enum SortAEnum implements SortX<A, B, C> {
SortA {
public void startClick(A a, B b, C c) {
newOne(a, b, c);
}
}, SortB {
public void startClick(A a, B b, C c) {
otherfunction(a);
}
}, SortB {
public void startClick(A a, B b, C c) {
someotherfunction(c, a);
}
}
}
public static void startClick(A a, B b, List<C extends OnClick> lstC, SortX sort){
for (int i=0; i<lstC.size(); i++){
sort.startClick(a, b, lstC.get(i));
}
}
关于Java/重构开关盒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20953054/