-
Notifications
You must be signed in to change notification settings - Fork 14
/
Observer.kt
56 lines (49 loc) · 1.19 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
47
48
49
50
51
52
53
54
55
56
package org.vld.sdp.behavioral
/**
* Observer interface
*/
interface BidObserver {
/**
* Notifies bid change from [oldBid] to [newBid]
*/
fun updateBid(oldBid: Int, newBid: Int)
}
/**
* Subject interface
*/
interface AuctioneerSubject {
/**
* Registers new [bidObservers] with the Subject
*/
fun register(vararg bidObservers: BidObserver)
/**
* Notifies the [BidObserver] of the [newBid] state change
*/
fun notifyNewBid(newBid: Int)
}
/**
* Subject interface implementation
*/
class Auctioneer : AuctioneerSubject {
// current bid
private var bid: Int = 0
// list of bidders to notify when the bid changes
private val bidders: MutableList<BidObserver> = mutableListOf()
override fun register(vararg bidObservers: BidObserver) {
bidders.addAll(bidObservers)
}
/**
* Notifies all [BidObserver]s with the new bid state change
*/
override fun notifyNewBid(newBid: Int) {
val oldBid = bid
bid = newBid
bidders.forEach { it.updateBid(oldBid, newBid) }
}
}
/**
* Observer implementation
*/
open class Bidder : BidObserver {
override fun updateBid(oldBid: Int, newBid: Int) {}
}