2

我有以下设计问题:

/**
 * Those 2 traits are the public API
 */
trait Box {
  def include(t: Token): Box
}
trait Token

/**
 * Implementation classes
 */
case class BoxImpl(id: Int) extends Box {
  /**
   * the implementation of this method depends on the implementation
   * of the Token trait
   * TODO: REMOVE asInstanceOf
   */
  def include(t: Token) = BoxImpl(t.asInstanceOf[TokenImpl].id + id)
}
case class TokenImpl(id: Int) extends Token

// use case
val b: Box = new BoxImpl(3)
val o: Token = new TokenImpl(4)

// == BoxImpl(7)
b.include(o)

在上面的代码中,我不想id在公共 API 中公开(甚至没有将其设置为,private[myproject]因为这仍然会在我的项目中包含循环依赖项)。

什么方法可以让公共 API 保持完整,同时让实现类彼此之间有一定的可见性(没有丑陋的演员表)?

4

1 回答 1

5

输入参数或成员:

trait Box {
  type T <: Token
  def include(t: T): Box
  //def include(t: Token): Box
}
trait Token

case class BoxImpl(id: Int) extends Box {
  type T = TokenImpl
  def include(t: T) = BoxImpl(t.id + id)

  /*
  def include(t: Token) = t match {
    case ti: TokenImpl => BoxImpl(ti.id + id)
    case _ => throw new UnsupportedOperationException
  }
  */

  //def include(t: Token) = BoxImpl(t.asInstanceOf[TokenImpl].id + id)
}
case class TokenImpl(id: Int) extends Token

有很多切片和切丁的方法,因此蛋糕图案,众所周知的一块蛋糕:

trait Boxer {
  type Token <: Tokenable
  trait Box {
    def include(t: Token): Box
  }
  trait Tokenable
}

trait Boxed extends Boxer {
  type Token = TokenImpl
  case class BoxImpl(id: Int) extends Box {
    override def include(t: Token) = BoxImpl(t.id + id)
  }
  case class TokenImpl(id: Int) extends Tokenable
}

trait User { this: Boxer =>
  def use(b: Box, t: Token): Box = b.include(t)
}

object Test extends App with Boxed with User {
  val b: Box = new BoxImpl(3)
  val o: Token = new TokenImpl(4)
  println(use(b, o))
}
于 2012-10-26T01:10:59.827 回答