Kotlin decorator pattern: Modifying component behavior
Write a Kotlin object-oriented program that implements the decorator pattern by creating a base class Component and decorator classes BoldDecorator and ItalicDecorator to modify the behavior of the component.
Sample Solution:
Kotlin Code:
Sample Output:
Original: Original component: Kotlin OOP Bold Decorator: <b>Original component: Kotlin OOP</b> Italic Decorator: <i>Original component: Kotlin OOP</i> Bold Italic Decorator: <i><b>Original component: Kotlin OOP</b></i>
Explanation:
In the above exercise -
- We have an interface Component that defines the common behavior for all components. The ConcreteComponent class implements the Component interface, representing the original component.
- "TextDecorator" is an abstract class that implements the Component interface and holds a reference to another component. It acts as a base class for specific decorators.
- "BoldDecorator" and "ItalicDecorator" are concrete decorator classes that extend "TextDecorator". They override the render() method to modify the wrapped component's behavior. In this case, they add HTML tags <b> and <i> to the rendered text.
- In the main() function, we create instances of the original component and different decorators. The decorators modify the original component's behavior by calling render() on each of them.
Kotlin Editor:
Previous: Handling operation results.
Next: Creating animal instances.
What is the difficulty level of this exercise?
Based on 1 votes, average difficulty level of this exercise is Medium
.
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics