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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.