** Table of Contents ** This pattern is to let other objects monitoring it do something at the same time when the properties of one object are updated.
It's an image that notifies the monitored object that the updated object has been updated. This is the Live Data of Android Architecture Components.
Define a one-to-many dependency between objects so that when an object changes state, all objects that depend on it are automatically notified and updated.
ยท Subject Observed abstract class -Observer Abstract class you want to monitor -ConcreteSubject A monitored concrete class -ConcreteObserver The concrete class you want to monitor
We will implement a sample program that is automatically updated when the application installed on the smartphone is updated. The play store is the subject and the smartphone is the observer. I don't implement an abstract class because it's annoying.
It is a play store.
PlayStore.kt
package observer
class PlayStore {
interface UpdateListener {
fun update(latestVersion: Int)
}
private val listeners = ArrayList<UpdateListener>()
fun update(latestVersion: Int) {
println("The sample app${latestVersion}It has been updated to.")
listeners.forEach {
it.update(latestVersion)
}
}
fun addListener(listener: UpdateListener) {
listeners.add(listener)
}
}
Implement two classes to observe so that you can easily feel the effect of this pattern.
First user who has the sample app installed
SnakeSmartPhone.kt
package observer
class SnakeSmartPhone(playStore: PlayStore) {
init {
playStore.addListener(object: PlayStore.UpdateListener {
override fun update(latestVersion: Int) {
println("Snake's smartphone app${latestVersion}The sample was updated to.")
}
})
}
}
Second user who has the sample app installed
Raiden.kt
package observer
class RaidenSmartPhone(playStore: PlayStore) {
init {
playStore.addListener(object: PlayStore.UpdateListener {
override fun update(latestVersion: Int) {
println("Raiden's smartphone sample app${latestVersion}It has been updated to.")
}
})
}
}
Client.kt
package observer
class Client {
init {
val playStore = PlayStore()
SnakeSmartPhone(playStore)
RaidenSmartPhone(playStore)
playStore.update(1)
playStore.update(2)
}
}
[out-put]
The sample app has been updated to 1.
Snake's smartphone sample app has been updated to 1.
Raiden's smartphone sample app has been updated to 1.
The sample app has been updated to 2.
Snake's smartphone sample app has been updated to 2.
Raiden's smartphone sample app has been updated to 2.
Every time you update the play store app, the smartphone on which it is installed is automatically updated.
that's all
Recommended Posts