Scala Listener/Observer

后端 未结 4 1222
庸人自扰
庸人自扰 2020-12-28 19:52

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 mor

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-28 20:33

    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.

    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. :)

提交回复
热议问题