Practical Patterns
Decorators with delegation.
The Decorator Pattern
A decorator wraps an object to add behavior while keeping the same interface. Kotlin's by keyword makes decorators trivial: forward everything, override the parts you enhance.
A Base Component
We start with a simple data source. The decorators will wrap this.
interface DataSource {
fun fetch(): String
}
class NetworkSource : DataSource {
override fun fetch() = "raw-data"
}
fun main() {
println(NetworkSource().fetch())
}All lessons in this course
- The by Keyword
- Delegating to Members
- Delegation vs Inheritance
- Practical Patterns