我试图重构下一个案例:
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}
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试创建和对象一个对象,就像我们在这里看到的那样:http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
所以我创建一个对象:SortOfType,然后对每一种情况下,我也创建一个对象(SortA,SortB,SortC).SortOfType获取实例的函数Gen,以及其他Sort对象.我没有成功的是调用类Gen的sortOfType.我该怎么做?这种重构是可能的吗?
您可以定义在需要操作时调用的接口
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));
}
}
Run Code Online (Sandbox Code Playgroud)