Java / Refactoring开关案例 [英] Java / Refactoring switch case
问题描述
我正在尝试重构下一个案例:
I am trying to refactor the next case:
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}
}
}
我尝试创建对象并对其进行处理,就像我们在这里看到的那样: http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
I try to create to and case an object, like we see here: http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
所以我创建了一个对象: SortOfType
,然后对于每种情况,我也创建一个对象( SortA
, SortB
, SortC
)。 SortOfType
中的函数获取 Gen
的实例,以及其他Sort对象。我没有成功的是将GenOfType称为类Gen.我该怎么做?这里可以进行这种重构吗?
So I create an object: SortOfType
, and then for each case I create also an object (SortA
, SortB
, SortC
). The function in SortOfType
get the instance of Gen
, and so the other Sort objects. What I don't success is to call the sortOfType fron the class Gen. How can I do it? this refactoring is possible here?
推荐答案
你定义了一个在需要动作时调用的接口
You define an interface which is called when an action is required
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 / Refactoring开关案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!