Saturday, November 13, 2010

..........Decorator Pattern

A Decorator design pattern is a design pattern that allows new/additional behavior to be added to an existing object dynamically.

The decorator pattern can be used to extend the functionality of certain object at runtime, independently of other instances of the same class. This is achieved by designing a new decorator class that wraps the original class.

We have to follow following steps for that :-
1) Subclass the original “Component” class or interface into a decorator class(Window is Component interface in below example).
2) In the decorator class add a component pointer as a field( CWindowDecorator is an added class here to add more functionality.)
3) Pass a component to the decorator constructor to initialize the component pointer.
4) In the Decorator class, redirect all Component methods to the component pointer.
5) In the Decorator class override any component methods whose behaviour need to be modified.


Suppose we have a window interface :-

// the Window interface
interface IWindow
{
public void draw(); // draws the Window
public String getDescription(); // returns a description of the Window
}

And a Simple Window class

// implementation of a simple Window without any scrollbars
class CSimpleWindow : Window
{
public void draw()
{
// draw window
}
}
public String getDescription()
{
return "simple window";
}
}

Suppose we want to add Vertical Scroll Bar into it.

//abstract decorator class - note that it implements Window
abstract class CWindowDecorator : IWindow
{
protected IWindow decoratedWindow; // the Window being decorated

public CWindowDecorator (IWindow decoratedWindow)
{
this.decoratedWindow = decoratedWindow;
}

public void draw()
{
decoratedWindow.draw();
}

public void getDescription()
{
decoratedWindow.getDescription();
}
}

Now we can add new functionality to the methods in new subclass of WindowDecorator.

// the first concrete decorator which adds vertical scrollbar functionality
class CVerticalScrollBarDecorator : CWindowDecorator
{
public CVerticalScrollBarDecorator (IWindow decoratedWindow)
{
base(decoratedWindow);
}

public void draw()
{
drawVerticalScrollBar();
base.draw();
}

private void drawVerticalScrollBar()
{
// draw the vertical scrollbar
}

public String getDescription()
{
return decoratedWindow.getDescription() + ", including vertical scrollbars";
}
}


How to use there classes.

public class CDecoratedWindowTest
{
public static void main(String[] args)
{
// create a decorated Window with horizontal and vertical scrollbars
IWindow decoratedWindow = new CVerticalScrollBarDecorator(new CSimpleWindow()));

// print the Window's description
Consloe.Writeline(decoratedWindow.getDescription());
}
}

.Output : Simple Window Including Vertical ScrollBar

No comments:

Followers

Link