具有发布者和订阅者特征的 Scala 类
使用 import scala.collection.mutable.{Publisher, Subscriber} 我试图实现一个订阅事件和发布事件的类。例如,此类可以接收原始数据,对其进行操作,然后将结果发布给其他订阅者。
扩展订阅者的基本类:
scala> class Sub[Evt, Pub]() extends Subscriber[Evt, Pub]{
def notify(pub: Pub, evt: Evt){
}
}
defined class Sub
扩展发布者的基本类:
scala> class Pub[Evt]() extends Publisher[Evt]{}
defined class Pub
现在,我想将两者结合起来:
scala> class PubSub[Evt, Pub] extends Subscriber[Evt, Pub] with Publisher[Evt]{
def notify(pub: Pub, evt: Evt){
}
}
<console>:26: error: class PubSub needs to be abstract, since method notify in
trait Subscriber of type (pub: Pub,event: Evt)Unit is not defined class
PubSub[Evt,Pub] extends Subscriber[Evt, Pub] with Publisher[Evt]{
定义了通知方法,因此该错误可能会产生误导。
我不确定如何定义 PubSub 类的类型参数,这可能是问题的一部分。
Using import scala.collection.mutable.{Publisher, Subscriber} I'm trying to implement a class that subscribes to events and publishes events. For example, this class may receive raw data, operate on it, then publish the result to other subscribers.
A basic class that extends Subscriber:
scala> class Sub[Evt, Pub]() extends Subscriber[Evt, Pub]{
def notify(pub: Pub, evt: Evt){
}
}
defined class Sub
A basic class that extends Publisher:
scala> class Pub[Evt]() extends Publisher[Evt]{}
defined class Pub
Now, I want to combine the two:
scala> class PubSub[Evt, Pub] extends Subscriber[Evt, Pub] with Publisher[Evt]{
def notify(pub: Pub, evt: Evt){
}
}
<console>:26: error: class PubSub needs to be abstract, since method notify in
trait Subscriber of type (pub: Pub,event: Evt)Unit is not defined class
PubSub[Evt,Pub] extends Subscriber[Evt, Pub] with Publisher[Evt]{
The notify method is defined so perhaps the error is misleading.
I'm not sure how to define the type parameters for the PubSub class which might be part of the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是 Publisher 类定义了一个 Pub 类型,它掩盖了通用 Pub 参数。
只需将其重命名为其他名称即可:
The problem is that the class Publisher defines a type Pub which shadows the generic Pub argument.
Just rename it to something else:
我相信您应该看看弃用观察者模式论文。那里描述的 scala.react 包并未作为标准发行版的一部分发布,但作者的 主页。如果您现在不打算在生产系统中使用它,那么这个项目可以提供足够的游乐场。
You should take a look at the paper Deprecating the Observer Pattern I believe. scala.react package described there isn't released as a part of the standard distribution, but some snapshot is available on the author's homepage. If you are not planning to use it in production systems right now this project can give a sufficient playground.