When do we need decorator pattern?
Asked Answered
S

9

35

When is it necessary to use the decorator pattern? If possible, give me a real world example that is well-suited for the pattern.

Stableman answered 13/8, 2010 at 14:44 Comment(3)
You need to tell us what you need to do if you want to know whether a decorator pattern would be useful, if you just want a general example just look up Decorator Pattern on wikipedia.Vibraculum
@BenRobinson I've read the Wikipedia article, and still am looking for better examples.Merna
Possible duplicate of When to Use the Decorator Pattern?Merna
F
53

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

Fragmental answered 13/8, 2010 at 14:51 Comment(2)
Yes, java.io is totally about Decorator.Recalescence
+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**.Inseparable
U
24

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.

Utham answered 13/8, 2010 at 15:30 Comment(5)
Is it implemented with the decorator pattern? It seems a list of strategies would work just as well.Merna
@JosiahYoder in strategy pattern behavior changes at run time,only one at a time but in Decorator pattern you add additional behavior to the existing behavior.Hominoid
@HameedSyed Do the Diablo or Final Fantasy 7 "slots" or "upgrades" act as objects? The decorator pattern also has an "is-a" relationship between the decorator and the decorated object. What is the decorator here? What is the decorated object?Merna
@JosiahYoder I am not aware of this game but I can explain with a file stream example which you can relate to the game if possible. Consider a filestream which must implement InputStream in order to work properly,now this is 'is a' relationship and is a decorator .But again you want to add speed to this filestream so you decorate with BufferInputStream . Now again you want to zip this BufferInputStream ,so you decorate more add ZipStream and so on.This additional decoration(BufferInputStream ,ZipStream ) to the decorated object(filestream ) is a Decorator pattern.Hominoid
@HameedSyed Thank you. I was hoping that the video game example could be fleshed out. I use the input stream example in my courses but was looking for something that students could relate to better.Merna
W
8

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.

Whoredom answered 13/8, 2010 at 14:48 Comment(1)
Do real-world UI's use this sort of decorator?Merna
V
5

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.

Varick answered 13/8, 2010 at 14:47 Comment(0)
S
3

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 [link] 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.

Sheliasheline answered 13/8, 2010 at 14:57 Comment(2)
The Head First PDF link is 404.Stpeter
@james.garriss: fixedClod
C
3

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.

Cheatham answered 13/8, 2010 at 15:10 Comment(0)
F
2

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.

Fascine answered 13/8, 2010 at 15:3 Comment(2)
@JosiahYoder - Updated the link. Thanks!Fascine
It would also be nice to incorporate one of the small code-snippets to complete the example and reduce the dependence on the link.Merna
T
1

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.

Treadle answered 13/8, 2010 at 14:50 Comment(0)
D
0

When is it necessary to use the decorator pattern?

Use Decorator_pattern if

  1. Object responsibilities and behaviours should be dynamically added/removed
  2. Concrete implementations should be decoupled from responsibilities and behaviours
  3. subclassing is too costly to dynamically add/remove responsibilities

If possible, give me a real world example that is well-suited for the pattern.

I have come up with my own Vending Machine Decorator.

Problem statement: Compute the price of Beverage (Tea or Coffee) by adding one or more flavours like Sugar, Lemon etc.

Code example and explanation is available @

When to Use the Decorator Pattern?

Dipsomania answered 13/8, 2016 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.