Implementing the Strategy pattern
The Strategy design pattern is used to provide an interchangeable set of strategies that can be applied to a given input and return an output of a specific type. We can understand the concept of a strategy as an action or an algorithm that can be applied to the input. A mechanism responsible for processing input should be able to switch between provided strategies at runtime. To illustrate the Strategy pattern, we are going to implement a text-formatting mechanism that allows us to apply a transformation to the input text and print it to the console. We are going to implement a class called Printer
, which will provide a printText(text: String)
function for printing the text to the console. Before printing out the text to the console, the Printer
class will perform a transformation of the given text
parameter according to the selected text formatting strategy.
How to do it...
- Implement the
Printer
class:
class Printer(val textFormattingStrategy: (String) ...