Scala 监听器/观察器
通常,在 Java 中,当我有一个对象向其他对象提供某种通知时,我将采用侦听器/观察者模式。
有没有更类似于 Scala 的方法来做到这一点?我应该在 Scala 中使用这种模式,还是我应该利用语言中的其他内容?
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您仍然可以积累回调列表,但您可以使它们发挥作用,而不必提出另一个单一方法接口。
例如,
另请阅读这篇有点相关的论文< /a> 如果您想服用红色药丸。 :)
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.
e.g.
Also read this this somewhat-related paper if you feel like taking the red pill. :)
是的。阅读 Ingo Maier、Tiark Rompf 撰写的论文弃用观察者模式,和马丁·奥德斯基。
更新 27-Apt-2015: 还有一个更新的 使用 Scala.React 弃用观察者模式,作者:Maier 和 Odersky。
Yes. Read the paper Deprecating the Observer Pattern by Ingo Maier, Tiark Rompf, and Martin Odersky.
Update 27-Apt-2015: There is also a more recent Deprecating the Observer Pattern with Scala.React by Maier and Odersky.
该代码片段与 Java 中带有一些 Scala 功能的代码片段非常相似。这是来自 Dean Wampler 的博客 - http ://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i
这使用了一些 Scala 功能,例如由 [S] 表示的泛型,特征类似于 Java 接口,但更强大,:: 将观察者添加到观察者列表中,以及使用 _ 计算当前观察者的参数的 foreach。
This snippet is pretty similar to what one would find in Java with some Scala features. This is from Dean Wampler's blog - http://blog.objectmentor.com/articles/2008/08/03/the-seductions-of-scala-part-i
This uses some Scala features such as generics as denoted by the [S], traits which are like Java interfaces but more powerful, :: to prepend an observer to the list of observers, and a foreach with the parameter using an _ which evaluates to the current observer.
您可以使用 scala.collection.mutable.Publisher 和 scala.collection.mutable.Subscriber 创建 pub/sub 实现
You can use scala.collection.mutable.Publisher and scala.collection.mutable.Subscriber to create a pub/sub implementation