【问题标题】:scala: how to model a basic parent-child relationscala:如何建模基本的父子关系
【发布时间】:2012-04-21 20:09:49
【问题描述】:

我有一个包含多个产品的 Brand 类

在产品类中,我想引用品牌,如下所示:

case class Brand(val name:String, val products: List[Product])

case class Product(val name: String, val brand: Brand)

如何填充这些类???

我的意思是,除非我有品牌,否则我无法创造产品

除非我有产品列表,否则我无法创建品牌(因为 Brand.products 是 val)

模拟这种关系的最佳方法是什么?

【问题讨论】:

    标签: oop scala relationship


    【解决方案1】:

    我会质疑您为什么要重复这些信息,即说明哪些产品与列表和每个产品中的哪个品牌相关。

    不过,你可以做到:

    class Brand(val name: String, ps: => List[Product]) {
      lazy val products = ps
      override def toString = "Brand("+name+", "+products+")" 
    }
    
    class Product(val name: String, b: => Brand) { 
      lazy val brand = b
      override def toString = "Product("+name+", "+brand.name+")"
    }
    
    lazy val p1: Product = new Product("fish", birdseye)
    lazy val p2: Product = new Product("peas", birdseye)
    lazy val birdseye = new Brand("BirdsEye", List(p1, p2))
    
    println(birdseye) 
      //Brand(BirdsEye, List(Product(fish, BirdsEye), Product(peas, BirdsEye)))
    

    不幸的是,案例类似乎不允许使用按名称参数。

    另请参阅此类似问题:Instantiating immutable paired objects

    【讨论】:

    • 这确实是我要找的东西,我在 repl 上试了一下,它告诉我没有找到 birdeye,我必须使用 :paste 模式,它工作正常,但正如你说,不支持案例类:-(
    • 我添加了品牌参考以便能够以两种方式遍历它,但我想在功能方法中它带来的麻烦多于优势......我说的对吗?
    • @opensas 这有点让人头疼,但有时是必要的。否则你必须使用vars 作为字段并且有nulls 的风险,但是这个版本是安全的
    【解决方案2】:

    既然你的问题是关于模型与这种关系的,我会说为什么不像我们在数据库中所做的那样对它们进行建模?分离实体和关系。

    val productsOfBrand: Map[Brand, List[Product]] = {
        // Initial your brand to products mapping here, using var
        // or mutable map to construct the relation is fine, since
        // it is limit to this scope, and transparent to the outside
        // world
    }
    case class Brand(val name:String){
        def products = productsOfBrand.get(this).getOrElse(Nil)
    }
    case class Product(val name: String, val brand: Brand) // If you really need that brand reference
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2021-01-28
      • 2019-08-04
      • 2011-03-12
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多