Decorator

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”

Design Patterns: Elements of Reusable Object-Oriented Software

Imagine the time before fancy and automatic GUIs, and the case of a simple textview. Sometimes, we enter more information in it than it can show. The behavior which we are accustomed to in these cases is that suddenly a scrollbar will appear out of nowhere, and magic! we can scroll down to see the rest of the text entered. But do we always need that scrollbar? If we’d create a subclass for textview with the name TextViewWithScrollBar, and use it anyway, would it make sense?

No it wouldn’t, we’d only need those bars whenever we exceed the space given us within the textview. And we cannot see that fore. So what is the solution?

From the title, you can guess easily that it’s nothing else but the Decorator pattern. Notice the following: “Attach additional responsibilities to an object dynamically.”. Not a class, but an instance of a given class, the object. This is the key phrase here. But how can we achieve such behavior. The answer is simple, we need four players here:

  • Component: a very brief and lightweight interface for your objects that can have dynamic responsibilities (such as render a scrollbar).
  • ConcreteComponent: the object itself which implements Component.
  • Decorator: implements Component, and maintains a reference to a ConcreteComponent.
  • ConcreteDecotator: adds the dynamic responsibilities to ConcreteComponent, implements Decorator.

Now a code example for the above:

//Component
public interface Window
{
                public void Draw() ;
 }
//ConcreteComponent
class TextView :Window
{
                public void Draw()
                {
                //Draw the TextView
}
}
//Decorator
abstract class WindowDecorator: Window
{
protected Window toDecorate;
public void Draw();
}
class ScrollBarDecorator: WindowDecorator
{
                public void Draw()
                {
                DrawBars();
                toDecorate.Draw();
                }
                private void DrawBars()
                {
                //Draw the scrollbars
                }
}

You see it isn’t hard by any means. And this helps you avoid the complexity of managing different subclasses for simple tasks.

Further Readings

Decorator Pattern on Wikipedia

Design Patterns (book): pp 175-184

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: