我正在编写一些类,它们都实现了从接口(interface)继承的特定方法。除了对某个其他函数的一次调用之外,此方法对于所有类都接近相同。
例如:
public void doSomething(){
int a = 6;
int b = 7;
int c = anOtherMethod(a,b);
while(c < 50){
c++;
}
}
如果多个类都有函数 doSomething() 但方法 anOtherMethod() 的实现不同怎么办?
在这种情况下如何避免代码重复? (这不是我的实际代码,而是一个简化版本,可以帮助我更好地描述我的意思。)
最佳答案
这看起来像是 template method pattern 的一个很好的例子。 .
- 将
doSomething
放入基类中。 - 也在该基类中声明
abstract protected anotherMethod
,但不提供实现。 - 每个子类都会为
anotherMethod
提供正确的实现。
关于java - 避免类上的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51813558/