问题
I have following classes:
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();
}
}
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.
回答1:
I assume what is being asked here is to use 'Polymorphism'
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();
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);
....
and so on
Because IBaseInterface has method baseMethod(), now you can simply iterate through the list and invoke baseMethod() method for each IBaseInterface objects.
take a look for 'Polymorphic Behavior'
来源:https://stackoverflow.com/questions/43086489/how-refactor-two-methods-which-are-very-similar