Junior — Middle
Can you give an example of a pattern responsible for object creation in programming?
sobes.tech AI
Answer from AI
One of the popular patterns responsible for object creation is the Factory Method. It allows creating objects without specifying the exact class of the object being created, delegating the creation to subclasses.
Example in Kotlin for Android:
// Product interface
interface Button {
fun render()
}
// Concrete product
class AndroidButton : Button {
override fun render() {
println("Drawing Android button")
}
}
// Factory
abstract class Dialog {
abstract fun createButton(): Button
fun renderDialog() {
val button = createButton()
button.render()
}
}
// Concrete factory
class AndroidDialog : Dialog() {
override fun createButton(): Button {
return AndroidButton()
}
}
// Usage
fun main() {
val dialog: Dialog = AndroidDialog()
dialog.renderDialog()
}
This pattern helps separate object creation code from their usage, which improves the extendability and maintainability of the code.