Strategy

The Strategy pattern is used to dynamically change an algorithm. According to this pattern, we should define a common interface and a class that encapsulates a certain implementation for each algorithm. The following diagram shows how class hierarchy can be built in this case:

This diagram contains the ImageFormatter interface, which is implemented by the PngFormatter and JpegFormatter classes. The Image class contains the convert method that takes an instance of the ImageFormatter type. Consequently, we can pass any implementation of ImageFormatter and therefore change a converting algorithm at runtime.

The common interface for strategies may look like this:

interface ImageFormatter {
fun format(image: Image): Image
}

Implementations of algorithms may look as follows:

class PngFormatter: ImageFormatter {
override fun format(image: Image) = Image()
}

class JpegFormatter: ImageFormatter {
override fun format(image: Image) = Image()
}

Furthermore, the Image class contains the convert method:

class Image {
fun convert(formatter: ImageFormatter): Image = formatter.format(this)
}

The following snippet shows that we can apply different algorithms to the same object:

fun main() {
val image = Image()
val pngImage = image.convert(PngFormatter())
val jpegImage = image.convert(JpegFormatter())
}
..................Content has been hidden....................

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