Skip to content

Instantly share code, notes, and snippets.

@alibahaaa
Created February 5, 2023 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alibahaaa/1d58350d51154ca541b3af6395a11ad9 to your computer and use it in GitHub Desktop.
Save alibahaaa/1d58350d51154ca541b3af6395a11ad9 to your computer and use it in GitHub Desktop.
interface Coffee {
fun cost(): Double
fun ingredients(): String
}
class Espresso : Coffee {
override fun cost() = 2.0
override fun ingredients() = "Espresso"
}
abstract class CoffeeDecorator(private val coffee: Coffee) : Coffee {
override fun cost() = coffee.cost()
override fun ingredients() = coffee.ingredients()
}
class MilkDecorator(coffee: Coffee) : CoffeeDecorator(coffee) {
override fun cost() = super.cost() + 0.5
override fun ingredients() = "${super.ingredients()} + Milk"
}
class SugarDecorator(coffee: Coffee) : CoffeeDecorator(coffee) {
override fun cost() = super.cost() + 0.3
override fun ingredients() = "${super.ingredients()} + Sugar"
}
val coffee = Espresso()
println("Coffee: ${coffee.ingredients()} - Cost: ${coffee.cost()}")
val coffeeWithMilk = MilkDecorator(coffee)
println("Coffee with Milk: ${coffeeWithMilk.ingredients()} - Cost: ${coffeeWithMilk.cost()}")
val coffeeWithMilkAndSugar = SugarDecorator(coffeeWithMilk)
println("Coffee with Milk and Sugar: ${coffeeWithMilkAndSugar.ingredients()} - Cost: ${coffeeWithMilkAndSugar.cost()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment