Writing the code for the decorator pattern

To begin, we create four packages, each of which represents the components of the decorator pattern. These packages are named component, concretecomponent, decorator, and concretedecorator. This is shown in the following screenshot:

In our case, Window is our component. This is an interface that declares the getDescription() and getPrice() functions:

interface Window {
fun getDescription(): String
fun getPrice(): Double
}

We have three implementations of the component—LargeWindow, MediumWindow, and SmallWindow. These implementations are similar and look like the following:

class LargeWindow : Window {
internal var description: String
internal var price: Double

init {
description = "Large Window"
price = 50.00
}

override fun getDescription(): String {
return description
}
override fun getPrice(): Double {
return price
}
}

In these concrete implementations, we set the description and the price using the init block, which will be invoked during object initialization. The other two implementations vary in setting the description value to medium, small, and other appropriate prices.

Let's write a simple program that creates LargeWindow and print its description as well as the price:

fun main(args: Array<String>) {
var window: Window = LargeWindow()

println("Window description: ${window.getDescription()}")
println("Window price: $${window.getPrice()}")

}

Now let's run this code. We should expect this to print the Large Window description as well as its cost of $50, which is what we have set for the LargeWindow class:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset