【问题标题】:How does stackable pattern, in Scala, apply when you need more parameters当您需要更多参数时,Scala 中的可堆叠模式如何应用
【发布时间】:2016-03-15 16:18:52
【问题描述】:

遵循可堆叠特征的规范示例[1]:

trait Double extends IntQueue {
  abstract override def put(x: Int) { super.put(2 * x) }
}

如果我想动态设置常量“2”怎么办?

我有两个解决方案,但缺点相当大:

  1. 将方法putMultiplied添加到新特征MultiplyX

    trait Multiplier extends IntQueue {
      abstract override def putMultiplied(constant: Int, x: Int) { super.put(constant * x) }
    }
    

    但是这会破坏 stackable 属性,因为另一个 stackable trait 必须知道 putMultiplied 方法

  2. 为常量创建一个setter:

    trait Multiplier extends IntQueue {
      var constant //hihi a variable constant
      abstract override def put(x: Int) { super.put(constant * x)  }
    }
    

    但这看起来很奇怪,并且给调用者带来了负担,让调用者记住在每次调用之前设置constant

直观地说,我希望 trait 有一个构造函数参数:

    trait Multiplier(val constant: Int) extends IntQueue {
      abstract override def put(x: Int) { super.put(constant * x)  }
    }

但是我们都知道 trait 不支持参数。

我是否对这种模式与 Scala 特征的结合提出了太多要求? 这将如何解决?

[1]http://www.artima.com/scalazine/articles/stackable_trait_pattern.html

【问题讨论】:

    标签: scala design-patterns


    【解决方案1】:

    另辟蹊径:

       trait Multiplied extends IntQueue {
          def multiplier = 2
          abstract override def put(x: Int) { super.put(multiplier * x) }
       }
    

    然后你可以像这样实例化它:

       val triplingQueue = new ActualQueue with Multiplier {
          override def multiplier = 3
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-24
      • 1970-01-01
      • 2019-04-07
      • 2011-02-10
      • 1970-01-01
      • 2014-01-16
      相关资源
      最近更新 更多