Just found some interesting way of implementing Decorator design pattern in Python.
As Jason Smith said in his book (Elemental Design Patterns), “design patterns may be implemened in different ways in different programming languages”.
That’s said, design patterns are not some set of classes which will be implemented in a very similar way in different languages - they are just a way of doing something.
Thus, Decorator pattern is a way of wrapping some method’s or class’ behaviour. In Python it may be done with Context Managers:
This code will end up wrapping
print "foo" and
print "moo" methods with printing some HTML tags around ‘em:
That is interesting as it implements Decorator design pattern in a bit hard-coded way, but using language features, not OOP ones.
Compare it to the "standard" OOP implementation in Python:
This one looks a bit… ugly… right? And though Python does not really care of which type are
b, we may not need all this class hierarchy.
This is the might of context managers!