Decorator Pattern
[Blog 7]
A Decorator Pattern is one which allows more functions to be attached to an object in a flexible manner. [1] Functionality can be added without the need to subclass an object. The Decorator Pattern is also known as “Wrapper”. Unlike sub-classing, the decorator pattern allows the additional functionality to be added only to the object that is desired. With inheritance, if a function is added, then every sub-class will have that function which is not always desirable.
A real life example might be a Vehicle object having a special functionality of loading and unloading a wheelchair and another normal vehicle that does not need that functionality. If that function is inherited through the main vehicle class then every vehicle will have that feature which will not always be needed.
A software example might be a function to change the font type of text in a document which is applicable where text is used and which is not applicable in other situations for example, where images are used.
The big advantage of using decorator pattern is that the decorations/ functions can be added anywhere where the decorator is defined. That is, if the decorator pattern is associated to a pool of functions or appearance of an interface, then it can be applied to any object that might need the functions which are subclasses of the decorator class.
Moreover, the existing structure of the coding is not affected as decorator classes and functions are separate and can be added or removed during execution. And when applied to objects, only affect the object targeted and not other objects. Also, when sub-classing is not very suitable like in cases where classes are sub-classed again and again to add functionality, the decorator pattern can be used to easily prevent this.
Decorator patterns are well known to be used in object-oriented user interface toolkits. [2]
References:
[ref.1] - Design Patterns CD, Elements of Reusable Object-Oriented Software, by Erich Gamma et all, Addison Wesley Longman Inc.].
[ref.2] - Design Patterns CD, Elements of Reusable Object-Oriented Software, by Erich Gamma et all, Addison Wesley Longman Inc.]

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home