我有两个方法具有相同的列表和参数类型以及几乎相同的主体,但它们中的每一个都调用另一个函数来获取元素列表。更准确地说:
public void method1 (int a, int b) {
//body (the same in both of methods)
List<SomeObject> list = service.getListA(int c, int d);
//rest of the body (the same in both of methods)
}
public void method2 (int a, int b) {
//body (the same in both of methods)
List<SomeObject> list = service.getListB(int c, int d, int e);
//rest of the body (the same in both of methods)
}
在这种情况下,避免代码重复问题的最佳方法是什么?我考虑了策略模式,但参数列表存在差异。
更新:
public void method1 (int a, int b) {
//body (the same in both of methods)
int c = some_value;
List<SomeObject> list = service.getListA(a, b, c);
//rest of the body (the same in both of methods)
}
public void method2 (int a, int b) {
//body (the same in both of methods)
int c = some_value;
int d = another_value;
List<SomeObject> list = service.getListB(a, b, c, d);
//rest of the body (the same in both of methods)
}
所以有些变量是本地的,有些是通过参数传递的。