Each of the classes contains about 30 methods and almost a half of them are same or very similar. And soon I am going to add a third class which is in the same situation with these two classes. I feel it is a mess to maintain or change them. How can I refactor to avoid the duplicate code?
Here is a simplified version:
public class A extends ContentPanel{
private AMenuProvider menuProvider;
private ADefinitionTree tree;
public void sameMethod1(){
...
menuProvider.do();
tree.doSomething();
...
}
public void sameMethod2(){
...
menuProvider.do();
tree.doSomething();
...
}
public void differentMethodFromA(){
... // uses menuProvider and tree
}
...
// 10 similar methods and 20 different methods
}
public class B extends ContentPanel{
private BMenuProvider menuProvider;
private BDefinitionTree tree;
public void sameMethod1(){
...
menuProvider.do();
tree.doSomething();
...
}
public void sameMethod2(){
...
menuProvider.do();
tree.doSomething();
...
}
public void differentMethodFromB(){
... // uses menuProvider and tree
}
...
// 10 similar methods and 20 different methods
}
NOTE: BMenuProvider vs AMenuProvider and ADefinitionTree vs BDefinitionTree could be very different implementation, but they provide a lot of same methods. Each of them has some unique methods which the other does not have.
I thought about creating an abstract class and extend it, but it seems ugly wherever I put the menuProvider and tree attributes. I am not sure whether there is any design patterns or solutions. Please help me refactor the classes so that I can remove the duplicate code.
Aucun commentaire:
Enregistrer un commentaire