Scala & the Decorator design pattern
As mentioned in my previous article about the Proxy design pattern, the ability to add features to an existing abstraction without involving an explicit extension of this abstraction is basically the purpose of the Decorator design pattern.
So, this article is simply a recap of the way to implement a Decorator using the technique based on implicit conversion.
Imagine you have a very useful class implementing a plain old feature. Imagine that you want to add a new great feature without subclassing anything.
Here is what you could do:
The Decorator pattern is basically realized by the decorator implicit conversion.
Note that the [T <% VeryUsefulClass] is important here: it means that the decorator will be applied to any type that can be seen as VeryUsefulClass, including any instance that is not explicitly a VeryUsefulClass instance but can be implicitly converted to a VeryUsefulClass instance, using an implicit conversion again: In fact the implicit conversion feature allows to revisit the classical Decorator Pattern, but what I presented corresponds to the Pimp my Library pattern as define in an article by Martin Odersky.
So, this article is simply a recap of the way to implement a Decorator using the technique based on implicit conversion.
Imagine you have a very useful class implementing a plain old feature. Imagine that you want to add a new great feature without subclassing anything.
Here is what you could do:
The Decorator pattern is basically realized by the decorator implicit conversion.
Note that the [T <% VeryUsefulClass] is important here: it means that the decorator will be applied to any type that can be seen as VeryUsefulClass, including any instance that is not explicitly a VeryUsefulClass instance but can be implicitly converted to a VeryUsefulClass instance, using an implicit conversion again: In fact the implicit conversion feature allows to revisit the classical Decorator Pattern, but what I presented corresponds to the Pimp my Library pattern as define in an article by Martin Odersky.
