Decorator Design Pattern

Last modified on September 12th, 2014 by Joe.

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.

Design of decorator pattern

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.

Decorator Design Pattern – UML Diagram


Implementation of decorator pattern

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";
  }
}

Execution of the decorator pattern

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());
  }

}

Output

Base Icecream + cruncy nuts + sweet honey

Decorator Design Pattern in java API

java.io.BufferedReader;
java.io.FileReader;
java.io.Reader;

The above readers of java API are designed using decorator design pattern.

Comments on "Decorator Design Pattern"

  1. Muralidhar says:

    Good Explanation with implementation.

    Can you please write about facade design pattern in brief..

    Thanks in advance.

  2. Jigar says:

    Great explanation for decorator design pattern

  3. Praveen says:

    Simple and clean example for decorator design pattern!
    Probably Visitor is also good design pattern to bring on the desk.

    Thank you.

  4. Shubhashish says:

    Nice article with simple example which is indeed a recipe of the good knowledge material. ;-)

  5. mahendra says:

    Good explanation for decorator design pattern with gr8 example.

  6. Amit says:

    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.

  7. Maniganda Prakash says:

    Nice article. Please correct the spelling mistake (cruncy -> crunchy).

  8. Anonymous says:

    Thanks for great explanation !!

  9. Swagatika says:

    Too good explanation with easy to understand examples. Thanks for the article.

  10. Sunitha PV says:

    Good article!!!! Decorator pattern is an alternative for subclassing. Subclassing adds behavior at compile time. But decorator add it runtime.

  11. Goldest says:

    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…

  12. Karthik says:

    Thank you very much for the nice Article very good explanation with example.

  13. Madhusudhan S says:

    All the articles here are very informative, clear and neatly presented. A BIG Thank you!!

  14. mani says:

    bad

  15. l says:

    bad

  16. anonymuous says:

    I liked when you mentioned the practical usage of pattern. As a reader.

  17. Navanethan says:

    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?

  18. Safayar says:

    Nice explanation of decorator pattern. Thank you.

  19. Suhas says:

    Neat and awesome blo.g

  20. Satyajeet Kadam says:

    I really appreciate your work.You have explained very nicely with small example.

  21. Shekar says:

    Very informative… I like the way things are explained in a simple way…
    Thanks a lot… It really helped me

  22. Ali Kaim Khani says:

    Neat+Clean and Easy explanation. Get cleared about Decorator… Many thanks
    Ali

  23. Siva says:

    Hi joseph,

    can u explain about MVP pattern.

  24. skay says:

    Hi Joe,
    Its fun to read and understand.I love the no-nonsense approach

    Thanks

  25. dhanya says:

    Nice explanation

  26. prakash says:

    good one can i get ur ph.no please…..
    i too very much curious abt knowing things deeply!!!!!!!!!!!!!

  27. barom says:

    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.

  28. Anonymous says:

    Very nice explanation…thanx

  29. Yajuvendra says:

    Very nice article and really very nice look and feel of this site.

  30. Rakesh says:

    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

  31. Pavan says:

    Good !!!

  32. brijesh says:

    ultimate example..

  33. subba says:

    Hi,

    Its clean example with explanation. Keep it up :)

  34. ssk says:

    Really appreciate your work. Explained very well.

    Thanks.

  35. Bobs says:

    Excellent job. Appreciate you work

  36. Krishna Jayanth says:

    Really good explanation, this i best explantion for decorator pattern..

    Thanks :-)

  37. Jayant says:

    Decorator pattern does not get as simple as this.
    Thanks Joe

  38. Akki says:

    Thanks Joe .. its one of best and simplest example of decorator design pattern ..

  39. Raj says:

    nice questions

  40. steven says:

    Simply superb
    Thanks.

  41. pavan says:

    nice explanation

  42. Anonymous says:

    That’s awesome!!
    This explanation was a tremendous help!
    Wish you all the best.
    Thanks a lot Sir.

  43. Basma says:

    That’s awesome!!
    This explanation was a tremendous help!
    Wish you all the best.
    Thanks a lot Sir.

  44. Inbakumar says:

    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.

  45. Atish Kumar says:

    Nice man ………

  46. German says:

    Excellent article !

  47. Ganesh Shinde says:

    Hi, I have doubt about the decorators design pattern, hunny and nutty these are flavors not an icecream but still inherited from the icecream.

  48. Anonymous says:

    Simple and super………

  49. Anonymous says:

    neat and simple

  50. Antony says:

    Hi

    Good example…. Keep posting!!!!

    Thanks
    Antony

  51. Sachin says:

    Nice explaination!! :)
    Similar explainations for other patterns too, will be helpfull ;)

  52. Sheena says:

    Simple & understandable. :-)

  53. Selman says:

    Good explanation. Thanks

  54. Anonymous says:

    Really good one with example along with the usage in the Java API.
    Thanks Satish.

  55. Mangeet S Eden says:

    Nice Explainations.

    Can you please also explain Chain of Reponsibility Pattern with real world example.

  56. hari says:

    good. appreciate

  57. chandra says:

    Nice article. Sperb

  58. Anonymous says:

    Nice explanation. Thanks a lot for the effort.Keep posting such awesome stuff!!!

  59. Anup Nair says:

    Nice explanation. Thanks a lot for the effort.Keep posting such awesome stuff!!!

  60. Resmi M S says:

    good .. i liked the explanation

  61. Anonymous says:

    I’ve searched a lot for a good example and i finally found it. Thanks man!

  62. prem says:

    I tried implementing the above example in eclipse IDE and got NullPointerException in the overridden method makeIceCream() of both implemented subclasses.

  63. Branka D.M. says:

    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!

  64. Arunava Sinha says:

    Nice and simple example

  65. VIswa says:

    Nice Article

  66. Lawrence says:

    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.

  67. Anonymous says:

    good explanation

  68. Waheed Khan says:

    Hmm … a very simple and elegant explaination.

  69. Harry says:

    I’ve programmed your sample and still no icecream! Where am I going wrong?!

  70. Anonymous says:

    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..

  71. Satish says:

    Thanks for clear explanation

  72. vitthalss says:

    superb…!

  73. Martinez says:

    why abstract class is required in decorator pattern?

    Can you explain it please.

  74. mandar says:

    thank you !!
    Really helpful article !!

  75. Shadab says:

    there is no need to put the method implementation in the abstract decorator class

    public String makeIcecream() {
    return specialIcecream.makeIcecream();
    }

  76. Clóvis says:

    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.

  77. priti says:

    GOOD Explanation……

  78. nitin says:

    wao so nicely explained, thanks

  79. yellaiah says:

    Very good example for decoration design pattern.. Keep itup.

  80. vivek says:

    What a simple and meaningful article with simple real world example…
    Now I have been forced to read other stuff in your blog.. :)

  81. Anonymous says:

    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.

  82. Anonymous says:

    Good work mate…………..saved the day

  83. Desa says:

    Good Work

  84. himanshu says:

    well done

  85. Krishnahari says:

    Cool explanation, Can you also put some simple and good example about factory design pattern as well. thanks in advance

    :)

  86. Soban says:

    cha gay ho yar. nice explanation

  87. soothing says:

    nice explaination,nice picture

  88. Gelandwagen says:

    Respect Bro =)

  89. Prabhu Ramaswamy says:

    Excellent.,

  90. Manzar Baig says:

    Thanks!! It’s simply awesome explanation.

  91. Manzar Baig says:

    What is replacement approach of Deocrator pattern. I mean if we do not implement Decorator.

  92. Anonymous says:

    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 :)

  93. Olobas says:

    atleast clear

  94. raj says:

    V Good Explanation Joe. Thank you

  95. Kishore says:

    Joe…You are extremly great. Thanks for the information. Waiting for more topics.

  96. Anonymous says:

    Good Explaination..

  97. Sudhakaru says:

    Very good example with clear explanation.
    Thanks lot.

  98. Pari says:

    Superb!

  99. Anonymous says:

    Thank you so much for your perfect explanation

  100. Prasad says:

    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

  101. Alex says:

    Very helpful with preparation for my exam and clear explanation without too much mumbo jumbo. Thanks a lot!

  102. kokot says:

    man, great article! very simple and easy to understand!! you should explain all patterns like this!

  103. Jordan says:

    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.

  104. Ahmed ALI EMAM says:

    Great explanation

  105. Anonymous says:

    simply gr8

  106. Anonymous says:

    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…………

  107. karthik says:

    very nice article

  108. Sekhar says:

    Awsm explanation ….. enjoyed this tutorial… keep it up .. :)

  109. achiever01 says:

    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!!

  110. ravi says:

    Sir, Your explanation and real time examples are very nice and excellent and also easy to understand.
    code is also very clean and convenient.

  111. Anonymous says:

    nice

  112. Anonymous says:

    I Think there should be Composition between Component and Decorator ,not the aggregation.

  113. Anonymous says:

    Agree this.

  114. kamal says:

    Excellent article

  115. RAgs says:

    Thanks good article

  116. Venkat says:

    Very nice explanation. Thanks a lot.

  117. Ramasamy says:

    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.

  118. AMIT CHAUDHARY . says:

    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 ?

  119. Anonymous says:

    Nice explanation:-) Too good:-)Thanks a lot.

  120. Anonymous says:

    Excellent!

  121. puligilla says:

    What advantage does this pattern over inheritance. ?
    We can achieve the same thing with inheritance also.

  122. Anonymous says:

    hi Joe, kindly reply to the questions asked when you get time.
    thanks,
    regular reader

  123. Anonymous says:

    Agree this!

Comments are closed for "Decorator Design Pattern".