Scalable Component Abstractions
  • Read Date - 2020-02-16
  • Fixed SubjectObserver example,
1
abstract class SubjectObserver {
2
type S <: Subject
3
type O <: Observer
4
​
5
abstract class Subject {
6
self : S =>
7
​
8
private var observers: List[O] = List()
9
​
10
def subscribe(obs: O): Unit = observers = obs :: observers
11
​
12
def publish(): Unit =
13
for (obs <- observers) obs.notify(self)
14
}
15
​
16
abstract class Observer {
17
def notify(sub: S): Unit
18
}
19
}
20
​
21
object SensorReader extends SubjectObserver {
22
type S = Sensor
23
type O = Display
24
​
25
abstract class Sensor extends Subject {
26
val label: String
27
var value: Double = 0.0
28
​
29
def changeValue(v: Double): Unit = {
30
value = v
31
publish()
32
}
33
}
34
​
35
class Display extends Observer {
36
override def notify(sub: Sensor): Unit =
37
println(s"${sub.label} has value ${sub.value}")
38
}
39
​
40
}
Copied!
Last modified 1yr ago
Copy link