java - 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.scala
which is has object B
with different constants and the same body of class A
duplicated as class B
(class B
使用里面的常量object B
)。
重构此代码的最佳方法是什么?我只想有一个类,并以某种方式基于对象改变其行为。
解决方案
定义:
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
推荐阅读
- oracle-apex - 创建一个将在 apex 中更新数据库表的按钮
- oop - 哪种设计模式允许我实现两个不同的类,每个类都有另一个类的对象列表?
- gdb - GDB:在调用函数之前显示函数的参数
- sql - SQL数据库中如何统计每个用户ID的出现次数
- substrate - 基板官方安装指南
- python - Flask ImportError:无法在heroku上导入名称'app'
- python - [Errno 2]:即使文件存在,也没有此类文件或目录错误
- javascript - 当我尝试向其添加 ++ 运算符时,它在 JS 中不起作用
- clojure - 如何避免 Clojure 中嵌套的“for”函数?
- typescript - 为什么这里有“隐式任何返回类型”错误?