You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala两个实现完全相同的类如何重构消除重复代码

Scala 重复类实现重构方案

核心思路

抽象常量定义层,将公共业务逻辑收敛到单个实现类,不同的常量集合通过实现统一的常量接口注入到通用类中,完全消除重复的类实现代码。

具体实现步骤

  1. 定义统一的常量抽象特质,声明所有需要用到的常量字段
trait CommonConstants {
  def SOME_CONSTANT: String
  // 其余所有公共常量的声明都放在此处
}
  1. 不同常量集合的伴生对象实现上述特质,填入对应的常量值
// a.scala 中的定义
object A extends CommonConstants {
  override val SOME_CONSTANT: String = "some_constant_a"
  // 其余A场景的常量实现

  def apply(arg: String): CommonClass = new CommonClass(arg, this)
}

// b.scala 中的定义
object B extends CommonConstants {
  override val SOME_CONSTANT: String = "some_constant_b"
  // 其余B场景的常量实现

  def apply(arg: String): CommonClass = new CommonClass(arg, this)
}
  1. 保留唯一的公共实现类,接收常量实例作为构造参数,所有业务逻辑只在此处实现一次
class CommonClass(arg: String, constants: CommonConstants) {
  // 原来 class A、class B 的所有公共逻辑都迁移到此处
  // 使用常量时直接引用constants下的对应字段即可
  def demoFunc(): String = s"${constants.SOME_CONSTANT}_${arg}"
}

方案优势

  • 彻底消除类实现的重复代码,后续业务逻辑修改只需要调整CommonClass一处
  • 常量定义和业务逻辑完全解耦,新增常量场景只需要新增实现CommonConstants的伴生对象,无需修改公共逻辑
  • 调用方式完全兼容原有习惯,原有调用A("xxx")、B("xxx")的代码不需要做任何调整
  • 支持单测时自定义常量实现,不需要依赖真实的伴生对象常量

可选简化写法

如果不希望显式传入常量参数,也可以通过隐式参数简化调用,只要在对应伴生对象的作用域中提供隐式常量实例即可:

class CommonClass(arg: String)(implicit constants: CommonConstants) {
  // 业务逻辑和上面一致
}

// 伴生对象中提供隐式实例
object A extends CommonConstants {
  override val SOME_CONSTANT: String = "some_constant_a"
  implicit val constants: CommonConstants = this
  def apply(arg: String): CommonClass = new CommonClass(arg)
}

内容的提问来源于stack exchange,提问作者1010101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:27:02