-
Notifications
You must be signed in to change notification settings - Fork 108
/
Observer.kt
46 lines (35 loc) · 1.11 KB
/
Observer.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package design_patterns
/**
*
* Observer is is a behavioral design pattern that defines a one-to-many relationship between objects
*
* such that when the state of one object changes all dependent objects are automatically notified and updated
*
*/
fun interface PonyObserver {
fun update(item: List<String>)
}
interface PonyObservable {
fun addObserver(observer: PonyObserver)
fun removeObserver(observer: PonyObserver)
fun notifyObservers()
}
// PonyList contains some data and when it changes we will notify observers
class PonyList : PonyObservable {
private val ponies = mutableListOf<String>()
private val observers = mutableSetOf<PonyObserver>()
fun add(pony: String) {
ponies.add(pony)
// notify observers that the data has changed
notifyObservers()
}
override fun addObserver(observer: PonyObserver) {
observers.add(observer)
}
override fun removeObserver(observer: PonyObserver) {
observers.remove(observer)
}
override fun notifyObservers() {
observers.forEach { observer -> observer.update(ponies) }
}
}