Decorator pattern

Another common case where Kotlin class delegation is really useful is when we are implementing a Decorator pattern. A Decorator pattern (also known as a Wrapper pattern) is a design pattern that makes it possible to add a behavior to an existing class without using inheritance. In contrast to extensions, where we can add a new behavior without modifying an object, we create a concrete object with a different behavior. A Decorator pattern uses delegation, but in a very specific way--a delegate is provided from outside of the class. The classic structure is presented in the following UML diagram:

UML diagram of a classic implementation ...

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.