Scala Listener/Observer

后端 未结 4 1248
庸人自扰
庸人自扰 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:16

    trait Observer[S] {
         def receiveUpdate(subject: S);
    }
    
    trait Subject[S] {
         this: S =>
         private var observers: List[Observer[S]] = Nil
         def addObserver(observer: Observer[S]) = observers = observer :: observers
    
         def notifyObservers() = observers.foreach(_.receiveUpdate(this))
    }
    

    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.

提交回复
热议问题