Application of Multiple Decorators on a Single Target
It is often necessary to apply more than one decorator on a single target. And as decorators can (and do) change the code that actually gets executed, it's important to have an understanding of how different decorators play together.
Basically, decorators are functions, and you're using them to compose your targets. This means that, in essence, decorators will be applied and executed bottom-up, with the decorator that's closest to the target going first and providing the result for the second decorators, and so on. This is similar to functional composition; that is, when we're trying to calculate f(g(x))
, first the g
function will be called, and then the f
function will be called.
There is a small catch when using decorator factories, though. The composition rule only applies to the decorators themselves – and decorator factories are not decorators per se. They are functions that need to be...