我写了一个实现命令设计模式的类:
class MyCommand[-T, +R](val name: String, val execute: T => R)
我已经为您准备好了两个命令并将其存储在MutableList中:
val commands = new mutable.MutableList[MyCommand[Nothing, Any]]
commands += new MyCommand[String, String]("lower", s => s.toLowerCase())
commands += new MyCommand[Date, Long]("time", d => d.getTime)
然后我有两条数据需要执行:
val data = Array("StRiNG", new Date())
对我来说问题在于我不知道如何确定哪个数据适用于该命令:
data.foreach {
d => commands.foreach {
c =>
// println(c.execute(d)) if d is applicable to c.execute().
}
}
我尝试使用类型规范进行模式匹配,但却产生了语法错误:
c.execute match {
case m: (d.getClass => Any) => println(c.execute(d))
}
帮帮我 :(