首页 > 解决方案 > Scala:两个具有相同实现的类

问题描述

我遇到了一些用 Scala 编写的代码,其结构如下

// a.scala
object A {
    def apply(arg: String) = {
         new A(arg)
    }
    // declare a bunch of constants
    val SOME_CONSTANT_A = "some_constant_a"
}

class A {
   // define functions that use SOME_CONSTANT_A and the other constants.
}

我们现在有b.scalawhich is has object Bwith different constants and the same body of class Aduplicated as class B(class B使用里面的常量object B)。

重构此代码的最佳方法是什么?我只想有一个类,并以某种方式基于对象改变其行为。

标签: javascalarefactoring

解决方案


定义:

class Base(private val constant: String) {
  def printConstant(): Unit = println(constant)
}

class A extends Base("constant_for_a")
class B extends Base("constant_for_b")

用法:

val a1 = new A()
a1.printConstant()
// constant_for_a

val b1 = new B()
b1.printConstant()
// constant_for_b

推荐阅读