简体   繁体   English

带有私有构造函数和scala工厂的类?

[英]Class with private constructor and factory in scala?

How do I implement a class with a private constructor, and a static create method in Scala? 如何在Scala中使用私有构造函数和静态create方法实现类?

Here is how I currently do it in Java: 以下是我目前在Java中的使用方法:

public class Tree {
    private Node root;

    /** Private constructor */
    private Tree() {}

    public static Tree create(List<Data2D> data) {
        Tree tree = new Tree();
        return buildTree(tree, data);//do stuff to build tree
    }

The direct translation of what you wrote would look like 你所写内容的直接翻译就像

class Tree private () {
  private var root: Node = null
}
object Tree { 
  def create(data: List[Data2D]) = {
    val tree = new Tree()
    buildTree(tree,data)
    tree
  }
}

but this is a somewhat un-Scalaish way to approach the problem, since you are creating an uninitialized tree which is potentially unsafe to use, and passing it around to various other methods. 但是这是一种解决问题的一种非Scalaish方法,因为你正在创建一个未初始化的树,它可能不安全使用,并将其传递给其他各种方法。 Instead, the more canonical code would have a rich (but hidden) constructor: 相反,更规范的代码将具有丰富(但隐藏)的构造函数:

class Tree private (val root: Node) { }
object Tree {
  def create(data: List[Data2D]) = {
    new Tree( buildNodesFrom(data) )
  }
}

if it's possible to construct that way. 如果有可能以这种方式构建。 (Depends on the structure of Node in this case. If Node must have references to the parent tree, then this is likely to either not work or be a lot more awkward. If Node need not know, then this would be the preferred style.) (在这种情况下取​​决于Node的结构。如果Node必须引用父树,那么这可能要么不起作用要么更难尴尬。如果Node不知道,那么这将是首选的样式。 )

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

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