Explanation of a java pattern and a very simple example a decorator pattern
By Gcinah
@Gcinah (1)
June 6, 2006 3:26pm CST
What is a deciorator pattern?.
How to use its?.Please give a understandable examplr
1 response
@anjuscor (1266)
• India
3 Jan 07
Design patterns are a staple of object-oriented design and programming by providing elegant, easy-to-reuse, and maintainable solutions to commonly encountered programming challenges.
The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.
A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains. That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators. This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.
The code for a decorator would something like this:
void doStuff() {
// any pre-processing code goes here.
aComponent.doStuff() // delegate to the decoree
// any post-processing code goes here
}

