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?
The Observer pattern (also known as Listener, or Publish-Subscribe) is particularly useful for graphical applications. The general idea is that one or more objects (the subscribers) register their interest in being notified of changes to another object (the publisher).
Professional Logo Design Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its depenedent objects are to be notified automatically. Observer pattern falls under behavioral pattern category.
Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state. The Observer pattern provides a way to subscribe and unsubscribe to and from these events for any object that implements a subscriber interface.
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With