Junior — Middle
Can you give an example of implementing a structural pattern in programming?
sobes.tech AI
Answer from AI
One of the popular structural patterns is the "Decorator" pattern. It allows dynamically adding new responsibilities to objects by wrapping them in other decorator objects.
Example in Kotlin for Android:
// Component interface
interface Coffee {
fun cost(): Double
}
// Concrete component
class SimpleCoffee : Coffee {
override fun cost() = 2.0
}
// Decorator
open class CoffeeDecorator(private val decoratedCoffee: Coffee) : Coffee {
override fun cost() = decoratedCoffee.cost()
}
// Concrete decorator
class MilkDecorator(coffee: Coffee) : CoffeeDecorator(coffee) {
override fun cost() = super.cost() + 0.5
}
// Usage
fun main() {
val simpleCoffee = SimpleCoffee()
val milkCoffee = MilkDecorator(simpleCoffee)
println("Cost of coffee with milk: ${milkCoffee.cost()}")
}
This approach allows flexible extension of functionality without changing the original class code.