如何重构两个非常相似的方法 [英] How refactor two methods which are very similar
问题描述
我有以下课程:
public interface IBaseInterface {
String baseMethod();
}
public class BaseClass implements IBaseInterface{
@Override
public String baseMethod() {
return "baseInterface";
}
public String otherBaseMethod(){
return "otherBaseMethod";
}
}
public class ClassA implements IBaseInterface{
@Override
public String baseMethod() {
return "ClassA";
}
public String getAttribiuteA(){
return "A";
}
}
public class ClassB implements IBaseInterface {
@Override
public String baseMethod() {
return "ClassB";
}
public String getAttribiuteB(){
return "B";
}
}
现在我有两个非常相似的方法:
And now I have two very similar methods:
private String getBaseMethod(){
/** Do something */
if(/** */){
BaseClass base = new BaseClass();
return base.baseMethod();
}else if (/** */){
ClassA a = new ClassA();
return a.baseMethod();
} else {
ClassB b = new ClassB();
return b.baseMethod();
}
}
private String getOtherMethod(){
/** Do something */
if(/** */){
BaseClass base = new BaseClass();
if(/** */){
return base.baseMethod();
} else{
return base.otherBaseMethod()
}
} else if(/** */){
ClassA a = new ClassA();
return a.getAttribiuteA()
} else{
ClassB b = new ClassB();
return b.getAttribiuteB();
}
}
这两种方法非常相似.在 if 子句中是相同的条件.我们可以把这两种方法做得更好吗?更抽象"?
These two methods are very similar. In if-Clause are the same conditions. Can we make these two methods better? More "abstractly" ?
我不能在我的类中做任何改变,只能在方法中.
I can not make any changes in my classes, only in methods.
推荐答案
我假设这里要求的是使用多态"
I assume what is being asked here is to use 'Polymorphism'
因为BaseClass、ClassA和ClassB这三个类都实现了interfcae IBaseInterface,所以你可以像下面的例子那样做:
Because all three classes, BaseClass, ClassA, and ClassB, all implement interfcae IBaseInterface, so you can do such thing like following example:
IBaseInterface i1 = new BaseClass();
IBaseInterface i2 = new ClassA();
IbaseInterface i3 = new ClassB();
正如您此时已经注意到的,您也可以使用 List 来保存您的类.
And as you already noticed at this point, you may use List to save your classes too.
List<IBaseInterface> interfaces = new ArrayList<>();
interfaces.add(i1);
....
等等
因为 IBaseInterface 有方法 baseMethod(),现在您可以简单地遍历列表并为每个 IBaseInterface 对象调用 baseMethod() 方法.
Because IBaseInterface has method baseMethod(), now you can simply iterate through the list and invoke baseMethod() method for each IBaseInterface objects.
看看多态行为"
这篇关于如何重构两个非常相似的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!