请参阅史蒂夫关于类型的回答self
和另一个代码示例。
这是一些使用观察者的示例代码。ObservedAccount
是观察者Subject
观察到的AccountReporter
。
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))
}
class Account(initialBalance: Double) {
private var currentBalance = initialBalance
def balance = currentBalance
def deposit(amount: Double) = currentBalance += amount
def withdraw(amount: Double) = currentBalance -= amount
}
class ObservedAccount(initialBalance: Double) extends Account(initialBalance) with Subject[Account] {
override def deposit(amount: Double) = {
super.deposit(amount)
notifyObservers()
}
override def withdraw(amount: Double) = {
super.withdraw(amount)
notifyObservers()
}
}
class AccountReporter extends Observer[Account] {
def receiveUpdate(account: Account) =
println("Observed balance change: "+account.balance)
}
让我们看看它的实际效果:
scala> val oa = new ObservedAccount(100.0)
oa: ObservedAccount = ObservedAccount@3f947e20
scala> val ar = new AccountReporter
ar: AccountReporter = AccountReporter@6ea70a98
scala> oa.addObserver(ar)
scala> oa.deposit(40.0)
Observed balance change: 140.0
scala> oa.withdraw(40.0)
Observed balance change: 100.0