A decorator also known as wrapper is an object that has an interface identical to an object it contains. Any call that the decorator gets, it relays to the wrapped object and add its own functionalities along the way, either before or after the call.
Example
- If we need to draw different borders for toolbar buttons, and one border may be applicable to more than one button. This can extend beyond border i.e. to other functionalities like color, font size etc.
- Suppose if we are developing our data access system and want to track each and every database call made by using java.sql objects, we can define decorator connection, statement and result set which can wrap any other data base object and can intercept the calls made by these.
When to Use
- When we need to add a common functionality to more than one class or objects.
- When extending a class for adding some functionality may duplicate the efforts across the classes.
- It is a very flexible way to add functionalities to any class without extending it.
- The same functionality can be added to more than one class without duplicating the code and efforts.
- It is applicable to both visual and non-visual programming elements.
- It enables us to add functionalities to any existing class without extending it.
- Decorator and its enclosed objects are not identical so object type test can fail.
- It results in a number of small objects in system which can be a maintenance headache for developer maintaining the system.
No comments:
Post a Comment