YFl*_*YFl 0 singleton design-patterns scala
假设我们有一个abstract class(也有同样的问题traits):
abstract class TypeParser[C <: Changes : TypeTag] extends Serializable {
val enrichmentType: EnrichmentType
protected def parseChanges(row: Row): C
}
Run Code Online (Sandbox Code Playgroud)
其中实现如下所示:
object PlaceholderParser extends TypeParser[PlaceholderChanges] {
val enrichmentType: EnrichmentType = PlaceholderType
override protected def parseChanges(row: Row): PlaceholderChanges = ???
}
Run Code Online (Sandbox Code Playgroud)
上面的实现是单例,但是,不能在将来的实现中强制它成为单例。因此,我们可以简单地将其实现为 a class,例如:
class PlaceholderParser2() extends TypeParser[PlaceholderChanges2] {
val enrichmentType: EnrichmentType = PlaceholderType2
override protected def parseChanges(row: Row): PlaceholderChanges2 = ???
}
Run Code Online (Sandbox Code Playgroud)
有没有办法强制实现成为单例?
附带问题:强迫它有什么好处吗?
为了我们的优势,所有这些都objects扩展了一个名为 的接口Singleton。你不能直接扩展它,但我们可以使用称为self-types 的Scala功能来强制 的所有子类型也为(即)TypeParserSingletons objects
abstract class TypeParser[C <: Changes : TypeTag] extends Serializable {
self: Singleton =>
...
}
Run Code Online (Sandbox Code Playgroud)