self
タイプと別のコード例については、Steveの回答を参照してください。
オブザーバーを使用したサンプルコードを次に示します。オブザーバーによって観察されるのは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