Created
February 5, 2023 09:49
-
-
Save alibahaaa/1d58350d51154ca541b3af6395a11ad9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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