Tuesday, 25 July 2017

Decorator pattern


I have a colleague who is officially a tester and scrummaster, and he has a growing interest in the code we (the developers) write. He asked a question this morning: "I've heard you talk about decorators, what are they?". I thought the best way to describe it is to write it down.


The decorator pattern allows you to add functionality to a class without changing the underlying class. (See Open/Closed principle)

As an example, there's a class that reticulates splines:

Imagine you wanted to add logging to this class, to store the number of splines reticulated. You could add the logging directly into the class:

Alternatively you could add a decorator (literally "decorate" the class with new behaviour). The idea behind the decorator pattern is that the decorating class implements the same interface as the underlying class, and wraps an instance of the underlying class. This way it can pass through to the underlying instance, and add value along the way.
This gives you the ability of adding several layers of behaviour, and swapping in and out that behaviour as and when required: