Decorator

AKA: Wrapper

You want to add a behaviour change to an object without changing the API or sub-classing. Perhaps it logs progress, but you want it also to ping you via email if the task has taken longer than ten minutes and looks like it’s less than 50% of the way through. But you only want to include this feature when needed. At this point, you want something suitably dynamic but not invasive to the existing class or object.

A Decorator adds behaviour before or after method calls by being of the same form as an object adapter, but instead of translating the API, it duplicates it. It hooks into the call and injects procedures where necessary to achieve the additional behaviour.

Decorator provides an inheritance-free form of overriding or introducing behaviour. If you can swap out the object, this allows for runtime mutability—the ability to add extra functions to an interface dynamically. Unlike class adapters, this also allows for “double” overriding. It’s like an inversion of a callback, so it pre-empts the original behaviour. It can pre or post do anything any number of times.

“I will unlock the doors before your work begins and lock them back up when you are done.”