Scala侦听器/观察者 [英] Scala Listener/Observer
问题描述
通常,在Java中,当我有一个对象正在向其他对象提供某种通知时,我将采用Listener/Observer模式.
Typically, in Java, when I've got an object who's providing some sort of notification to other objects, I'll employ the Listener/Observer pattern.
是否有更像Scala的方式来做到这一点?我应该在Scala中使用这种模式,还是我应该利用的语言中还包含其他一些东西?
Is there a more Scala-like way to do this? Should I be using this pattern in Scala, or is there something else baked into the language I should be taking advantage of?
推荐答案
您仍然可以积累一系列的回调,但是您可以使它们发挥作用,而不必提出另一个单独的方法接口.
You can still accumulate a list of callbacks, but you can just make them functions instead of having to come up with yet another single method interface.
例如
case class MyEvent(...)
object Foo {
var listeners: List[MyEvent => ()] = Nil
def listen(listener: MyEvent => ()) {
listeners ::= listener
}
def notify(ev: MyEvent) = for (l <- listeners) l(ev)
}
也请阅读此这有点相关纸(如果您想服用红色药丸). :)
Also read this this somewhat-related paper if you feel like taking the red pill. :)
这篇关于Scala侦听器/观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!