Centaur Tech

Dips

Monday, July 18

Decorate away...



Decorator Design Pattern :
Motive :
Attach additional responsibilities to "an existing object" dynamically (and not the entire class )
This pattern can be used instead of subclassing (which we generally do to extend functionality).

So the thumbrules are :
>> Decorator has the same interface as the object that it wants to 'decorate'.
eg : Decorator class implements component interface.
>> Decorator contains (wraps ) the base object within itself. (also referred to as Wrapper)
eg : Decorator class has an instance of the component object.
This way it can modify the behaviour of the component object, and it can be called as required (dynamic) i.e call ConcreteDecoratorB(Component a)

This can also be very effectively used in situations where modification by extending class behaviour is impractical, as in having too many possibilities of sub-classes , or base class is hidden or unavailable.
Eg : Provide filtering behaviour for Httprequest object.

The decorator HttpServletRequestWrapper will implement HttpServletRequest . Suppose it modifies the getParamaterValues operation to filter blanks.

The filter would then call it as follows :
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter( new MyRequestWrapper((HttpServletRequest) request), response);
}
This shows that within the bounds of defined behaviour (ie : method signature of doFilter method) , we can modify the behaviour of the underlying object using the Decorator pattern.

This article is simplistic enough in its approach , to make you totally understand Decorator pattern : Link

Dips at 6:06 PM

0 comments

0 Comments

Post a Comment