观察者模式 - 默认观察者

时间:2015-11-18 11:09:40

标签: scala observer-pattern

如何将观察者作为Observer模式中的默认观察者。例如,在此示例中,来自here

import scala.collection.mutable.ArrayBuffer

// Abstract implementation
trait Observable {
  val observers = ArrayBuffer[Observer]()

  def notifyObservers() {
    for(observer <- observers)
      observer.notification()
  }

  def addObserver(observer:Observer) {
    observers += observer
  }

  def removeObserver(observer:Observer) {
    observers -= observer
  }
}

trait Observer {
  def notification(): Unit
}

// Concrete Implementation
class SomeObservable extends Observable

class SomeObserver extends Observer {
  override def notification() {
    println("do something here: SomeObserver")
  }
}

class AnotherObserver extends Observer {
  override def notification() {
    println("do something here: AnotherObserver")
  }
}

// Client
object ObserverClient {
  def main(args: Array[String]) {
    val observable = new SomeObservable()
    val observer1 = new SomeObserver()
    val observer2 = new AnotherObserver()
    observable.addObserver(observer1)
    observable.addObserver(observer2)
    observable.notifyObservers()
    observable.removeObserver(observer2)
    observable.notifyObservers()
  }
}

我的担心也是,通过让观察者默认看到我如何静态通知而不是动态地通知观察者。

1 个答案:

答案 0 :(得分:1)

我这里没有Scala可以尝试,但你可以这样做:

import scala.collection.mutable.ArrayBuffer

object Observable {
   val defaultObserver = { create your default here to do what you want }
}

trait Observable {
  val observers = ArrayBuffer(Observable.defaultObserver)

  ... (the rest stays the same)

您希望通过函数删除默认观察者的额外点。