Decorator pattern in kotlin

Date published23.07.2017Time to read1 minutes read

If you feel curious how would an implementation of decorator design pattern look like in Kotlin, this might be the right place for you. This example is just a very basic thing that you then tweak until it’s perfect. Pattern definition can be found at Wiki, but what’s important is that you can compose chain of decorators at runtime and in such a way – you can control runtime behavior of your system.

package patterns

interface CarService {
    fun doService()
}

interface CarServiceDecorator : CarService

class BasicCarService : CarService {
    override fun doService() = println("Doing basic checkup ... DONE")
}

class CarWash(private val carService: CarService) : CarServiceDecorator {
    override fun doService() {
        carService.doService()
        println("Washing car ... DONE")
    }
}

class InsideCarCleanup(private val carService: CarService) : CarServiceDecorator {
    override fun doService() {
        carService.doService()
        println("Cleaning car inside ... DONE")
    }
}

fun main(args: Array<String>) {
    val carService = InsideCarCleanup(CarWash(BasicCarService()))
    carService.doService()
}

Program output:

Doing basic checkup ... DONE
Washing car ... DONE
Cleaning car inside ... DONE

That was all for today! Hope you liked it!