Kotlin patterns: Decorator pattern with class delegates
When you need to add some behavior to a class you have two choices:
- Extend it and create a subclass
- Use the decorator pattern to decorate the class with the new functionality.
When the class that you want to add some extra functions to is a non-extensible class, the only way to accomplish this is the second one.
The decorator pattern does 3 things:
- Creates a new class that has a field that is an instance of the class we want to decorate
- Overrides all its methods
- Add the extra functionality that we want.
This is a lot of code and boilerplate
Kotlin makes it really easy to create decorators using class delegation with the use of the by keyword.
In the example above we can see how we decorate a MutableList with functions that sends email when a new employee is added or removed from the list.
We don’t have to override the rest of the functions of MutableList to call theirs super method, Kotlin delegates will do it for us.
The decorator pattern is very useful and helpful and can reduce the complexity of our code. With the help of Kotlin’s delegation classes we can apply it in a very clean and easy way.