简体   繁体   English

Scala中的通用工厂(?)模式

[英]Generic factory (?) pattern in Scala

I have a generic class: 我有一个通用类:

class SomeValue[T](private val value: T) {
  override def toString = value.toString
}

In my application, I'm going to be using a particular construction of this class a lot: 在我的应用程序中,我将大量使用此类的特殊构造:

val five = new SomeValue[Int](5) // doing this a lot
assert(five.toString == "5")

This is pretty verbose and prone to typos (for example setting it to 6 by accident). 这很冗长,容易出现错别字(例如,偶然将其设置为6)。 To solve this, I'd like to create a class that masks this pattern: 为了解决这个问题,我想创建一个掩盖此模式的类:

class Five { ... }

So that I can now do this: 这样我现在可以执行以下操作:

val five = new Five
assert(five.toString == "5")

Kind of a dumb example I know, but hope you get the picture! 我知道一个愚蠢的例子,但希望您能理解!

It seems like you are building constants, hence I would suggest using Scala objects . 似乎您正在构建常量,因此我建议使用Scala对象

eg 例如

object Main extends App {
  assert(Five.toString == "5")
  assert(Hello.toString == "hello")
}

class SomeValue[T](private val value: T) {
  override def toString = value.toString
}

object Five extends SomeValue[Int](5)
object Hello extends SomeValue[String]("hello")

Why not just define a method instead of a whole new class? 为什么不仅仅定义一个方法而不是一个全新的类呢?

class SomeValue[T](private val value: T) { ... }
object SomeValue {
  // since the class appears to be immutable, it could also be a val
  def five = new SomeValue(5)
}

// elsewhere
SomeValue.five

Naturally, this method can have arguments and type arguments if desired (eg to fix only some of constructor arguments). 当然,如果需要,此方法可以具有参数和类型参数(例如,仅修复一些构造函数参数)。

Came up with this right after posting my question. 发表我的问题后马上想到。

class Five extends SomeValue[Int](value = 5) {}

Seems right, but can anyone confirm? 似乎正确,但有人可以确认吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM