Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Decorator Design Pattern - Kotlin
class DecoratorDesignPattern {
companion object {
@JvmStatic
fun main(args: Array<String>) {
val rose = RoseBouquet()
println("Without customization = ${rose.description}, ${rose.cost()}")
val roseWrapper = PaperWrapper(rose)
println("With customization = ${roseWrapper.description}, ${roseWrapper.cost()}")
val orchid = OrchidBouquet()
println("Without customization = ${orchid.description}, ${orchid.cost()}")
val orchidRibbon = RibbonBow(orchid)
println("With customization = ${orchidRibbon.description}, ${orchidRibbon.cost()}")
}
}
}
/**
* Base class for our Design Pattern.
*/
abstract class FlowerBouquet {
open var description: String = ""
/*
Child should override this method
*/
abstract fun cost(): Double
}
/**
* Extended from [FlowerBouquet]
*/
class RoseBouquet : FlowerBouquet() {
override fun cost(): Double = 12.0
init {
description = "Rose bouquet"
}
}
/**
* Extended from [FlowerBouquet]
*/
class OrchidBouquet : FlowerBouquet() {
override fun cost(): Double {
return 29.0
}
init {
description = "Orchid bouquet"
}
}
/**
* Here is the entry point for the Decorator Design Pattern.
* We want to achieve run-time functionalities for [FlowerBouquet] objects.
* All child that extend [FlowerBouquet] are eligible for this run-time functionalities.
*/
abstract class FlowerBouquetDecorator : FlowerBouquet() {
abstract override var description: String
}
/**
* Provide additional functionalities to [FlowerBouquet] objects.
* [PaperWrapper] take [FlowerBouquet] object instance as parameter for rum-time behaviour changes.
*
* @param flowerBouquet [FlowerBouquet] instance
*/
class PaperWrapper(private var flowerBouquet: FlowerBouquet) : FlowerBouquetDecorator() {
override var description: String = flowerBouquet.description + ", paper wrap"
override fun cost(): Double {
return 3 + flowerBouquet.cost()
}
}
/**
* Provide additional functionalities to [FlowerBouquet] objects.
* [PaperWrapper] take [FlowerBouquet] object instance as parameter for rum-time behaviour changes.
*
* @param flowerBouquet [FlowerBouquet] instance
*/
class RibbonBow(private var flowerBouquet: FlowerBouquet) : FlowerBouquetDecorator() {
override var description: String = flowerBouquet.description + ", ribbon bow"
override fun cost(): Double {
return 6.5 + flowerBouquet.cost()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment