Sobes.tech
Junior — Middle

Can you give an example of a behavioral design pattern?

sobes.tech AI

Answer from AI

A behavioral design pattern example is the "Observer" pattern. It is used when you need to notify multiple objects about changes in the state of another object.

In Android, this pattern is often used with LiveData and ViewModel, where the View subscribes to data changes and updates automatically.

Example in Kotlin:

class Subject {
    private val observers = mutableListOf<Observer>()
    var state: Int = 0
        set(value) {
            field = value
            notifyObservers()
        }

    fun attach(observer: Observer) {
        observers.add(observer)
    }

    private fun notifyObservers() {
        observers.forEach { it.update(state) }
    }
}

interface Observer {
    fun update(state: Int)
}

class ConcreteObserver : Observer {
    override fun update(state: Int) {
        println("State updated to: $state")
    }
}

fun main() {
    val subject = Subject()
    val observer = ConcreteObserver()
    subject.attach(observer)
    subject.state = 10
}
Can you give an example of a behavioral design… - sobes.tech