Decorators are just design patterns – python people – not HGTV

by Security Dude

The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class, provided some groundwork is done at design time. This is achieved by designing a new decorator class that wraps the original class. This wrapping could be achieved by the following sequence of steps:

  1. Subclass the original “Decorator” class into a “Component” class (see UML diagram);
  2. In the Decorator class, add a Component pointer as a field;
  3. Pass a Component to the Decorator constructor to initialize the Component pointer;
  4. In the Decorator class, redirect all “Component” methods to the “Component” pointer; and
  5. In the ConcreteDecorator class, override any Component method(s) whose behavior needs to be modified.

This pattern is designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality to the overridden method(s).

The decorator pattern is an alternative to subclassing. Subclassing adds behavior at compile time, and the change affects all instances of the original class; decorating can provide new behavior at run-time for individual objects.

This difference becomes most important when there are several independent ways of extending functionality. In some object-oriented programming languages, classes cannot be created at runtime, and it is typically not possible to predict, at design time, what combinations of extensions will be needed. This would mean that a new class would have to be made for every possible combination. By contrast, decorators are objects, created at runtime, and can be combined on a per-use basis. The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern.

http://en.wikipedia.org/wiki/Decorator_pattern

http://stackoverflow.com/questions/739654/understanding-python-decorators/1594484#1594484

http://www.doughellmann.com/PyMOTW/functools/

http://dabeaz.blogspot.com/2011/05/class-decorators-might-also-be-super.html

http://rhettinger.wordpress.com/2011/05/26/super-considered-super/

http://pythonconquerstheuniverse.wordpress.com/2012/08/12/enum-in-python/

http://www.rafekettler.com/magicmethods.html

Advertisements