避免代码重复

Pie*_*ein 2 java

我正在编写一些类,它们都实现了一个从接口继承的特定方法.除了对某个其他函数的一次调用之外,所有类的此方法都接近相同.

例如:

public void doSomething(){
    int a = 6;
    int b = 7;
    int c = anOtherMethod(a,b);
    while(c < 50){
        c++;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果多个类具有doSomething()函数但是anOtherMethod()方法的实现有何不同呢?

在这种情况下如何避免代码重复?(这不是我的实际代码,而是一个简化的版本,可以帮助我描述我的意思更好.)

Thi*_*ilo 5

这看起来像是模板方法模式的一个很好的例子.

  1. 放入doSomething基类.
  2. abstract protected anotherMethod也在该基类中声明,但不提供实现.
  3. 然后每个子类提供适当的实现anotherMethod.