1

我需要实现两个类似的过程,它们基本上执行相同的逻辑,但一些参数/方法可能会有所不同。我想知道将主要逻辑提取到父类并将一些方法的结果指定给子类是否是一个好习惯。就像是:

abstract class Parent{

protected CommonDao commonDao;

protected String specStatus;

protected abstract int getDbResult();

public Parent(CommonDao commonDao){
    this.commonDao = commonDao;
}

public String mainLogic(){
    if(commonMethod()){
    //..
    }
    int specDbResult = getDbResult();
    //some logic here

    return specStatus;
}

private boolean commonMethod(){ 
//.. 
return true;
}

}

@Service
public Child1 extends Parent(){

  @Autowired
  public Child1(CommonDao commonDao){
     super(commonDao);
     super.specStatus = specStatus1;
  }

  @Override
  protected String getDbResult(){
      commonDao.getResult1();
  }

}

@Service
public Child2 extends Parent(){

  @Autowired
  public Child2(CommonDao commonDao){
     super(commonDao);
     super.specStatus = specStatus2;
  }

  @Override
  protected String getDbResult(){
      commonDao.getResult2();
  }

}

如果它似乎不是一个干净的代码,在这种情况下你会推荐什么解决方案?提前致谢

4

1 回答 1

0

使用依赖注入,组合显然是比继承更好的方法

而 dao 作为属性对于父子关系是不够的

请确保您已了解有效 Java 的第 16 条,因为任何程序员都可能会 http://thefinestartist.com/effective-java/16

按要求编辑

@Service
public class NotAChild{

@Autowired
CommonOps1 commonOps1;

@Autowired
CommonOps2 commonOps2;

private boolean commonMethod(){ 
int result1 = commonOps1.getDbResult(); 
int result2 = commonOps2.getDbResult(); 
....
return result1 + result2;
}
}

@Component
public class CommonOpS1{

@Autowired
CommonDao commonDao;

protected String getDbResult(){
      commonDao.getResult1();
}

}

@Component
public class CommonOpS2{

@Autowired
CommonDao commonDao;

protected String getDbResult(){
      commonDao.getResult2();
}

}

所有其他 NotAChildN 对象都可以使用 CommonOps 的常用方法。

所以,你不会使用继承

于 2020-01-31T08:48:53.767 回答