To extend or modify the behaviour of ‘an instance’ at runtime decorator design pattern is used. Inheritance is used to extend the abilities of ‘a class’. Unlike inheritance, you can choose any single object of a class and modify its behaviour leaving the other instances unmodified.
In implementing the decorator pattern you construct a wrapper around an object by extending its behavior. The wrapper will do its job before or after and delegate the call to the wrapped instance.
You start with an interface which creates a blue print for the class which will have decorators. Then implement that interface with basic functionalities. Till now we have got an interface and an implementation concrete class. Create an abstract class that contains (aggregation relationship) an attribute type of the interface. The constructor of this class assigns the interface type instance to that attribute. This class is the decorator base class. Now you can extend this class and create as many concrete decorator classes. The concrete decorator class will add its own methods. After / before executing its own method the concrete decorator will call the base instance’s method. Key to this decorator design pattern is the binding of method and the base instance happens at runtime based on the object passed as parameter to the constructor. Thus dynamically customizing the behavior of that specific instance alone.
Following given example is an implementation of decorator design pattern. Icecream is a classic example for decorator design pattern. You create a basic icecream and then add toppings to it as you prefer. The added toppings change the taste of the basic icecream. You can add as many topping as you want. This sample scenario is implemented below.
package com.javapapers.sample.designpattern; public interface Icecream { public String makeIcecream(); }
The above is an interface depicting an icecream. I have kept things as simple as possible so that the focus will be on understanding the design pattern. Following class is a concrete implementation of this interface. This is the base class on which the decorators will be added.
package com.javapapers.sample.designpattern; public class SimpleIcecream implements Icecream { @Override public String makeIcecream() { return "Base Icecream"; } }
Following class is the decorator class. It is the core of the decorator design pattern. It contains an attribute for the type of interface. Instance is assigned dynamically at the creation of decorator using its constructor. Once assigned that instance method will be invoked.
package com.javapapers.sample.designpattern; abstract class IcecreamDecorator implements Icecream { protected Icecream specialIcecream; public IcecreamDecorator(Icecream specialIcecream) { this.specialIcecream = specialIcecream; } public String makeIcecream() { return specialIcecream.makeIcecream(); } }
Following two classes are similar. These are two decorators, concrete class implementing the abstract decorator. When the decorator is created the base instance is passed using the constructor and is assigned to the super class. In the makeIcecream method we call the base method followed by its own method addNuts(). This addNuts() extends the behavior by adding its own steps.
package com.javapapers.sample.designpattern; public class NuttyDecorator extends IcecreamDecorator { public NuttyDecorator(Icecream specialIcecream) { super(specialIcecream); } public String makeIcecream() { return specialIcecream.makeIcecream() + addNuts(); } private String addNuts() { return " + cruncy nuts"; } }
package com.javapapers.sample.designpattern; public class HoneyDecorator extends IcecreamDecorator { public HoneyDecorator(Icecream specialIcecream) { super(specialIcecream); } public String makeIcecream() { return specialIcecream.makeIcecream() + addHoney(); } private String addHoney() { return " + sweet honey"; } }
I have created a simple icecream and decorated that with nuts and on top of it with honey. We can use as many decorators in any order we want. This excellent flexibility and changing the behaviour of an instance of our choice at runtime is the main advantage of the decorator design pattern.
package com.javapapers.sample.designpattern; public class TestDecorator { public static void main(String args[]) { Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream())); System.out.println(icecream.makeIcecream()); } }
Base Icecream + cruncy nuts + sweet honey
java.io.BufferedReader;
java.io.FileReader;
java.io.Reader;
The above readers of java API are designed using decorator design pattern.
Comments are closed for "Decorator Design Pattern".
Good Explanation with implementation.
Can you please write about facade design pattern in brief..
Thanks in advance.
Great explanation for decorator design pattern
Simple and clean example for decorator design pattern!
Probably Visitor is also good design pattern to bring on the desk.
Thank you.
Nice article with simple example which is indeed a recipe of the good knowledge material. ;-)
Good explanation for decorator design pattern with gr8 example.
Good explanation with an easy to understand example. Another real time example could be decorating the data source used in the application. The decorator could be used to execute any additional global queries on the connection instance before the connection is handed over to the application. For e.g. if your application uses oracle as the db server and your application wants the executed queries to be case insensitive (note – oracle is case sensitive) one could execute the National Language Settings (NLS) queries on the connection instance before it used by the application.
Nice article. Please correct the spelling mistake (cruncy -> crunchy).
Thanks for great explanation !!
Too good explanation with easy to understand examples. Thanks for the article.
Good article!!!! Decorator pattern is an alternative for subclassing. Subclassing adds behavior at compile time. But decorator add it runtime.
Why did you change the blog theme? Thats so bad man… Previous theme was so awesome compared to this one… This theme sucks. Get back to the previous one if possible…
Thank you very much for the nice Article very good explanation with example.
All the articles here are very informative, clear and neatly presented. A BIG Thank you!!
bad
bad
I liked when you mentioned the practical usage of pattern. As a reader.
Hi, I became a fan of your blog, and I like very much the way of explanation, and I need a clarification on this IceCream example. Why do we have IcecreamDecorator and instead can I have HoneyIceCream extends from IceCream and it can hold simpleIceCream and other functions same?
Nice explanation of decorator pattern. Thank you.
Neat and awesome blo.g
I really appreciate your work.You have explained very nicely with small example.
Very informative… I like the way things are explained in a simple way…
Thanks a lot… It really helped me
Neat+Clean and Easy explanation. Get cleared about Decorator… Many thanks
Ali
Hi joseph,
can u explain about MVP pattern.
Hi Joe,
Its fun to read and understand.I love the no-nonsense approach
Thanks
Nice explanation
good one can i get ur ph.no please…..
i too very much curious abt knowing things deeply!!!!!!!!!!!!!
I love your description and example. Thank you. I’ve been studying this pattern for a while (for one of my classes, as in school) and I finally get it thanks to this explanation.
Very nice explanation…thanx
Very nice article and really very nice look and feel of this site.
Hi Joe,
The above explaination is remarkable. I am little bit confused on a particular piece of code,please help me out
Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
My confusion is that, we create an instance of inetrface so how do “new SimpleIcecream()” will work.
Please explain.
Regards,
Rakesh
Good !!!
ultimate example..
Hi,
Its clean example with explanation. Keep it up :)
Really appreciate your work. Explained very well.
Thanks.
Excellent job. Appreciate you work
Really good explanation, this i best explantion for decorator pattern..
Thanks :-)
Decorator pattern does not get as simple as this.
Thanks Joe
Thanks Joe .. its one of best and simplest example of decorator design pattern ..
nice questions
Simply superb
Thanks.
nice explanation
That’s awesome!!
This explanation was a tremendous help!
Wish you all the best.
Thanks a lot Sir.
That’s awesome!!
This explanation was a tremendous help!
Wish you all the best.
Thanks a lot Sir.
Hi Joe, Good analogy selected.
The relation between the IceCream and IceCreamDecorator is aggregation.
If you remove IceCreamDecorator, IceCream can still exist.
You have mentioned the relation as composition in class diagram.
kind excuse, if i am wrong.
Nice man ………
Excellent article !
Hi, I have doubt about the decorators design pattern, hunny and nutty these are flavors not an icecream but still inherited from the icecream.
Simple and super………
neat and simple
Hi
Good example…. Keep posting!!!!
Thanks
Antony
Nice explaination!! :)
Similar explainations for other patterns too, will be helpfull ;)
Simple & understandable. :-)
Good explanation. Thanks
Really good one with example along with the usage in the Java API.
Thanks Satish.
Nice Explainations.
Can you please also explain Chain of Reponsibility Pattern with real world example.
good. appreciate
Nice article. Sperb
Nice explanation. Thanks a lot for the effort.Keep posting such awesome stuff!!!
Nice explanation. Thanks a lot for the effort.Keep posting such awesome stuff!!!
good .. i liked the explanation
I’ve searched a lot for a good example and i finally found it. Thanks man!
I tried implementing the above example in eclipse IDE and got NullPointerException in the overridden method makeIceCream() of both implemented subclasses.
I’ve been researching Desing Patterns for a quite long time, and this is for sure one of the top 5 sites addressing this topic. As far I could find out there are just few websites with examples before and after design pattern is applied. Thanks a lot for your work! Greetings from Serbia!
Nice and simple example
Nice Article
Personally I find decorators to be a sign of flawed design. They conflict most with the AOP principles. A given class is designed to do 1 thing at best. Either the required functionality is not present and thus the class needs to be given that functionality or the functionality is not directly related to the class and thus you need to either extend it or simply use it’s methods and do something with the obtained data. But decorating makes maintenance extremely cumbersome because if changes occur, for every decorator you need to implement them and that costs time. I am convinces with better thinking you can almost always avoid them by using better alternatives.
good explanation
Hmm … a very simple and elegant explaination.
I’ve programmed your sample and still no icecream! Where am I going wrong?!
Thanks for the explanation, but in ur example is quite confusing..
” Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
System.out.println(icecream.makeIcecream());”
will not work as the Honey Decorator cannot take a IcecreamDecorator as argument.
Maybe u wanted to say, Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()).makeIcecream());
Excuse me, if I am wrong..
Thanks for clear explanation
superb…!
why abstract class is required in decorator pattern?
Can you explain it please.
thank you !!
Really helpful article !!
there is no need to put the method implementation in the abstract decorator class
public String makeIcecream() {
return specialIcecream.makeIcecream();
}
Excellent examples Joe. Quite didactic for those who are learning patterns like me. I would like to see an example of Observer. And another about MVC swing.
GOOD Explanation……
wao so nicely explained, thanks
Very good example for decoration design pattern.. Keep itup.
What a simple and meaningful article with simple real world example…
Now I have been forced to read other stuff in your blog.. :)
Do you really need to write the method makeIcecream() in the abstract decorator class? Why can’t it just be defined as abstract so concrete-decorators can implement it? They are doing whatever the base method is doing anyways.
Good work mate…………..saved the day
Good Work
well done
Cool explanation, Can you also put some simple and good example about factory design pattern as well. thanks in advance
:)
cha gay ho yar. nice explanation
nice explaination,nice picture
Respect Bro =)
Excellent.,
Thanks!! It’s simply awesome explanation.
What is replacement approach of Deocrator pattern. I mean if we do not implement Decorator.
I really appreciate your questions! it is so valid from good OOAD point of view.
You have raised question on basic fundamental of Object Design. To support your doubts I would like to give one more example.
We could not design Peacock and Flight in same family even fly() behavior is common for both of them.
Note:
Family is something related to extends the class and keep hierarchy. not exactly implements interface (Just hold on with this idea now.More Explanation you could see below)
Reasons for implementing Ice Cream Interface on Simple Ice Cream (Real one) and Decorators (Just for providing solution to modify the behavior of Real object).
a)Both should be same type.then only Decorator object can replace to Simple Ice Cream object in client side.
b) When we want to bridge many different family of classes (Peacock and Flight) that have common behavior(s) Interface is the solution instead of extends.
Here also we have two different family classes Decorators and Ice Creams (SimpleIceCream) that linked with IceCream Interface with common behavior makeIceCream ().
Hope it may help you :)
Thanks to Joe and guys shared your comments – good learning for me :)
atleast clear
V Good Explanation Joe. Thank you
Joe…You are extremly great. Thanks for the information. Waiting for more topics.
Good Explaination..
Very good example with clear explanation.
Thanks lot.
Superb!
Thank you so much for your perfect explanation
Hi Joe,
I have been following your articles regularly. The explanation above was just excellent with nice example. Hope we will get the same for the rest of design patterns as well.
Thanks,
prasad
Very helpful with preparation for my exam and clear explanation without too much mumbo jumbo. Thanks a lot!
man, great article! very simple and easy to understand!! you should explain all patterns like this!
Yeah, I still don’t see how this decorator business is NOT inheritance + junk code. Every article claims it’s dynamic and inheritance is static and every example fails to show the difference.
Great explanation
simply gr8
hii joe ,
Really nice but i don’t understand the flow of this program.
ex: how increamDecorator class know from which class makeIcream will called.
please provide this information because this question is ask by interviwer and i fail to givethis answer
thanks…………
very nice article
Awsm explanation ….. enjoyed this tutorial… keep it up .. :)
All your posts(specially the design patterns) are FABULOUS. They are very easy read and help a great deal specially for someone who is new to the area. Great work!! Keep Posting!!
Sir, Your explanation and real time examples are very nice and excellent and also easy to understand.
code is also very clean and convenient.
nice
I Think there should be Composition between Component and Decorator ,not the aggregation.
Agree this.
Excellent article
Thanks good article
Very nice explanation. Thanks a lot.
Hi joe,
Very nice post. I have bit confusion in this example.
How come the output like “Base Icecream + cruncy nuts + sweet honey”?
Because we have
protected Icecream specialIcecream;
in decorator class which is first is assigned to NuttyDecorator instance then again re-assigned to SimpleIcecream intance by the following line,
Icecream icecream = new HoneyDecorator(new NuttyDecorator(new SimpleIcecream()));
Hence the output of the following line will be Base Icecream + sweet honey
System.out.println(icecream.makeIcecream());
Please explain me.
Thanks.
Can i eliminate IcecreamDecorator at design time and design directly HoneyDecorator & NuttyDecorator which will implement Icecream interface creating makeicecream method at design time.
At runtime i will create object of Simple Icecream and pass that to HoneyDecorator & NuttyDecorator objects constructor.
Is it OK ?
Nice explanation:-) Too good:-)Thanks a lot.
Excellent!
What advantage does this pattern over inheritance. ?
We can achieve the same thing with inheritance also.
hi Joe, kindly reply to the questions asked when you get time.
thanks,
regular reader
Agree this!