views:

328

answers:

8

when do we need to go for Decorator pattern? If possible give me a real world example that suits that pattern...

+4  A: 

Have a look at the Fowler description; it gives a concrete example relating to books/videos and a decorator "borrowable", you can find it here.

Lazarus
+6  A: 

From Gang of Four:

A graphical user interface toolkit, for example, should let you add properties like borders or behaviors like scrolling to any user interface component.

...

The decorator conforms to the interface of the component it decorates so that its presence is transparent to the component's clients. The decorator forwards requests to the component and may perform additional actions (such as drawing a border) before or after forwarding. Transparency lets you nest decorators recursively, thereby allowing an unlimited number of added responsibilities.

Mike
+1  A: 

If you are familiar with Swing development in Java (along with other GUI toolkits), you'll see the decorator pattern used a lot. You might have a constructor that takes in a specific component and then adds functionality to it.

Here is a good article that uses Swing as an example.

Thomas Owens
+16  A: 

The Streams in Java - subclasses of InputStream and OutputStream are perfect examples of the decorator pattern.

As an example, writing a file to disk:

File toWriteTo = new File("C:\\temp\\tempFile.txt");
OutputStream outputStream = new FileOutputStream(toWriteTo);    

outputStream.write("Sample text".getBytes());

Then should you require some extra functionality regarding the writing to disk:

File toWriteTo = new File("C:\\temp\\tempFile.txt");
OutputStream outputStream = 
             new GZIPOutputStream(new FileOutputStream(toWriteTo));

outputStream.write("Sample text".getBytes());

By simply "chaining" the constructors, you can create quite powerful ways of writing to disk. The beauty in this way is that you can add different (in this example) OutputStream implementations later on. Also, each implementation doesn't know how the others work - they all just work to the same contract. This also makes testing each implementation very easy in isolation.


There are plenty of "real world" examples of where the decorator pattern can be used. Off the top of my head, some examples:

  • Reading and writing to disk (above)
  • Construction of UI elements, such as adding scrollbars on to text areas etc

Head First Design Patterns has some more "real world" examples. It seems that O'Reilly has their sample chapter, which is on Decorator Pattern, for free; Google showed up this link: PDF

Noel M
Yes, java.io is totally about Decorator.
duffymo
+1: lovely example :)
Juliet
+1 Though I don't regard the heavy use of the Decorator pattern in java.io as 'beautiful'. It's one the various reasons that file io in Java is such a pain in the a**.
Helper Method
+1  A: 

The intent of Decorator pattern is to:

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. [via Head First: Design Patterns]

The most heavy use of decorator pattern are GUIs and java.io classes. There is a free chapter of Head First: Design Patterns about decorator pattern [PDF] which provide some other examples:

We’ll re-examine the typical overuse of inheritance and you’ll learn how to decorate your classes at runtime using a form of object composition. Why? Once you know the techniques of decorating, you’ll be able to give your (or someone else’s) objects new responsibilities without making any code changes to the underlying classes.

You can also read Decorator Pattern by Example [PDF] in which decorator pattern is used in an evaluation application.

ventr1s
+1  A: 

You asked for a real-world example, so here you go: download (or browse) DonsProxy from github:

git://github.com/DonBranson/DonsProxy.git

DonsProxy basically uses a WireTap pattern to let you watch or extract HTTP traffic, plus it lets you modify the connection behavior to simulate suboptimal connections. I use the Decorator pattern to modify channels based on user options. Command-line or GUI options (dependinvg on which View they're using) allows latency injection and bandwidth injection, among other things. When they inject latency, that adds the LatencyDecorator to the channel; if they throttle the bandwidth, that adds the ThrottleDecorator to the channel. Since this use a decorator pattern, they can mix-and-match behavior to their heart's content.

Don Branson
+1  A: 

One of the coolest - and most literal - uses I've seen was to implement undo-ability, back in the bad old days of single-level undo. Given a vector drawing program, with several objects selected, of varying colors: implement a command to change all of their colors. And make it undo-able. This was done by applying a Decorator, which got invoked in the getColor() stream, so that when they were drawn, they got drawn in the new color; essentially the objects' own getColor() methods were overruled. So they showed up in the new color. To undo was as simple as removing the Decorator from all the objects; committing the action was a matter of applying the color from the Decorator to the objects and then removing it. Much simpler than keeping a table of which objects had been colored and what their original colors had been.

Carl Manaster
+3  A: 

Two real-life examples:

The item upgrading systems in Diablo 2 and Final Fantasy 7. Weapons and armor have sockets or slots. During the game, the player put upgrades (gems, runes or materia) into those slots. Each upgrade has an individual effect (say, 8 points fire damage or 10% mana leech). So when you swing your sword, it does its base damage plus the damage added by each upgrade you've added. This matches the decorator pattern extremely closely.