Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do we need decorator pattern?

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

like image 711
brainless Avatar asked Aug 13 '10 14:08

brainless


People also ask

What is the use of Decorator design pattern?

Decorator design pattern allows us to dynamically add functionality and behavior to an object without affecting the behavior of other existing objects within the same class. We use inheritance to extend the behavior of the class.

What is the applicability and example of decorator pattern?

This pattern creates a decorator class which wraps the original class and provides additional functionality keeping class methods signature intact. We are demonstrating the use of decorator pattern via following example in which we will decorate a shape with some color without alter shape class.


2 Answers

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

like image 196
Noel M Avatar answered Sep 20 '22 14:09

Noel M


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.

like image 44
user240515 Avatar answered Sep 21 '22 14:09

user240515