Real-world examples
The decorator pattern is generally used for extending the functionality of an object. In everyday life, examples of functionality extensions are adding a holder stand to a phone or using different camera lenses.
In the Django framework, which uses decorators a lot, we have the View
decorators, which can be used for the following (j.mp/djangodec):
- Restricting access to views based on the HTTP request
- Controlling the caching behavior on specific views
- Controlling compression on a per-view basis
- Controlling caching based on specific HTTP request headers
Both the Pyramid framework and the Zope application server also use decorators to achieve various goals, such as the following:
- Registering a function as an event subscriber
- Protecting a method with a specific permission
- Implementing the adapter pattern
To be more concrete, we will iterate the specific use cases of the design pattern in the next section.