Real-world examples
The decorator pattern is generally used for extending the functionality of an object. In everyday life, examples of such extensions are: adding a silencer to a gun, using different camera lenses, and so on.
In the Django Framework, which uses decorators a lot, we have the View
decorators which can be used for (j.mp/djangodec) the following:
- 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:
- Registering a function as an event subscriber
- Protecting a method with a specific permission
- Implementing the adapter pattern