Illustrating the observer pattern

Let's illustrate the observer pattern through the example of stock market data. Our use case here is that the observers will be registered for specific trades of a company and they will be observing for any changes in the data.

To design this model, let's write a simple contract. We will begin with the Subject and Observer interfaces.

The Subject interface has the following three functions:

  • fun register(observer: Observer)
  • fun remove(observer: Observer)
  • fun notify()

The register() function registers an Observer for observing the subject. The remove()  function will then remove dependent objects from observing Subject. The notify() function then sends a notification to all registered observers about the state change.

The Observer interface has one function:

fun update()

This function will be invoked by the subject while sending the notification. When this function is invoked, dependent objects will see the updated value for the stock price.

Let's provide an implementation class for the Subject interface, as follows:

class StockData : Subject {
internal var observerList: MutableList<Observer> = ArrayList()
var symbol: String ?= null
var price: Float? = null

override fun register(observer: Observer) {
observerList.add(observer)
}

override fun remove(observer: Observer) {
val i = observerList.indexOf(observer)
if (i >= 0) {
observerList.removeAt(i)
}
observerList.remove(observer)
}

override fun notify() {
for (i in observerList.indices) {
observerList[i].update()
}
}

fun setStockData(symbol: String, price: Float?) {
this.symbol = symbol
this.price = price
notifyObservers()
}
}

This StockData class maintains a list of observers for the stock-data change event. Here, the register() function adds the observer to the list and the remove() function takes the observer out of the list. The notify() function simply invokes update() on the observers that are registered.

An implementation of the Observer interface will have the definition for the update() function, which updates the required data in the observer.

We have now described the observer pattern and illustrated it using an example. This pattern is useful when we have multiple observers that are monitoring state-information changes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset