Junior — Middle
What is the role of the Delegation pattern in object-oriented programming and why is it used?
sobes.tech AI
Answer from AI
The Delegation pattern in object-oriented programming is a way of passing responsibility for executing a specific task to another object. Instead of the class implementing some functionality itself, it delegates it to another object that specializes in that task.
This allows:
- To divide responsibilities among classes, improving modularity.
- To increase code reuse.
- To simplify support and extension of functionality.
- To avoid inheritance where composition is sufficient.
For example, in Android, delegation is often used for event handling: an activity delegates button click handling to a separate listener object.
class ButtonHandler {
fun onClick() {
println("Button clicked")
}
}
class Activity {
private val handler = ButtonHandler()
fun buttonClicked() {
handler.onClick() // delegating handling
}
}