【问题标题】:Inheritance: main method in parent class with relation to specific implementation of a few methods in child继承:父类中的主要方法与子类中一些方法的具体实现有关
【发布时间】:2020-05-16 21:12:21
【问题描述】:

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

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();
  }

}

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

【问题讨论】:

  • 感谢您的评论。它看起来与我的代码相似,它也是某种算法,需要执行哪些步骤,但在我的代码中,孩子之间的大部分逻辑应该是相同的(因此粘贴到父类)。区别主要在于几个参数,调用另一个dao方法。

标签: spring inheritance template-method-pattern


【解决方案1】:

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

而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 的常用方法。

所以,你不会使用继承

【讨论】:

  • 您能详细说明一下吗?在这种情况下,我看不到如何重写我的代码。
  • 所以我认为 commonMethod() 将是我的算法。但是当有很多 CommonOpS 时,自动装配呢?
  • 框架创建你的组件。自动装配将其交给您的服务。如果您有许多组件,您可以自动装配服务所需的组件。我已经增强了示例
  • 这不是我想要的——我确实需要合并结果,我需要一次又一次地使用第二次。我认为模板方法在这里似乎是一个更好的解决方案
  • result1 + result2 在我看来就像合并结果。为什么不是?
猜你喜欢
  • 2011-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
相关资源
最近更新 更多