Decorator Design Pattern

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.

This Design Patterns tutorial was added on 17/05/2011.

Comments on "Decorator Design Pattern" Tutorial:

  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. anonymuous says:

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

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

  17. Safayar says:

    Nice explanation of decorator pattern. Thank you.

  18. Suhas says:

    Neat and awesome blo.g

  19. Satyajeet Kadam says:

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

  20. Shekar says:

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

  21. Ali Kaim Khani says:

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

  22. Siva says:

    Hi joseph,

    can u explain about MVP pattern.

  23. skay says:

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

    Thanks

  24. dhanya says:

    Nice explanation

  25. prakash says:

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

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

  27. Anonymous says:

    Very nice explanation…thanx

  28. Yajuvendra says:

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

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

  30. Pavan says:

    Good !!!

  31. brijesh says:

    ultimate example..

  32. subba says:

    Hi,

    Its clean example with explanation. Keep it up :)

  33. ssk says:

    Really appreciate your work. Explained very well.

    Thanks.

  34. Bobs says:

    Excellent job. Appreciate you work

  35. Krishna Jayanth says:

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

    Thanks :-)

  36. Jayant says:

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

  37. Akki says:

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

  38. Raj says:

    nice questions

  39. steven says:

    Simply superb
    Thanks.

  40. pavan says:

    nice explanation

  41. Anonymous says:

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

  42. Basma says:

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

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

  44. Atish Kumar says:

    Nice man ………

  45. German says:

    Excellent article !

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

  47. Anonymous says:

    Simple and super………

  48. Anonymous says:

    neat and simple

  49. Antony says:

    Hi

    Good example…. Keep posting!!!!

    Thanks
    Antony

  50. Sachin says:

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

  51. Sheena says:

    Simple & understandable. :-)

  52. Selman says:

    Good explanation. Thanks

  53. Anonymous says:

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

  54. Mangeet S Eden says:

    Nice Explainations.

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

  55. hari says:

    good. appreciate

  56. chandra says:

    Nice article. Sperb

  57. Anonymous says:

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

  58. Anup Nair says:

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

  59. Resmi M S says:

    good .. i liked the explanation

  60. Anonymous says:

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

  61. prem says:

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

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

  63. Arunava Sinha says:

    Nice and simple example

  64. VIswa says:

    Nice Article

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

  66. Anonymous says:

    good explanation

  67. Waheed Khan says:

    Hmm … a very simple and elegant explaination.

  68. Harry says:

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

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

  70. Satish says:

    Thanks for clear explanation

  71. vitthalss says:

    superb…!

  72. Martinez says:

    why abstract class is required in decorator pattern?

    Can you explain it please.

  73. mandar says:

    thank you !!
    Really helpful article !!

  74. Shadab says:

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

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

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

  76. priti says:

    GOOD Explanation……

  77. nitin says:

    wao so nicely explained, thanks

  78. yellaiah says:

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

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

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

  81. Anonymous says:

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

  82. Desa says:

    Good Work

  83. himanshu says:

    well done

  84. Krishnahari says:

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

    :)

  85. Soban says:

    cha gay ho yar. nice explanation

  86. soothing says:

    nice explaination,nice picture

  87. Gelandwagen says:

    Respect Bro =)

  88. Prabhu Ramaswamy says:

    Excellent.,

  89. Manzar Baig says:

    Thanks!! It’s simply awesome explanation.

  90. Manzar Baig says:

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

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

  92. Olobas says:

    atleast clear

  93. raj says:

    V Good Explanation Joe. Thank you

  94. Kishore says:

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

  95. Anonymous says:

    Good Explaination..

  96. Sudhakaru says:

    Very good example with clear explanation.
    Thanks lot.

  97. Pari says:

    Superb!

  98. Anonymous says:

    Thank you so much for your perfect explanation

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

  100. Alex says:

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

  101. kokot says:

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

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

  103. Ahmed ALI EMAM says:

    Great explanation

  104. Anonymous says:

    simply gr8

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

  106. karthik says:

    very nice article

  107. Sekhar says:

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

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

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

  110. Anonymous says:

    nice

  111. Anonymous says:

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

  112. Anonymous says:

    Agree this.

  113. kamal says:

    Excellent article

  114. RAgs says:

    Thanks good article

  115. Venkat says:

    Very nice explanation. Thanks a lot.

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

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

  118. Anonymous says:

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

  119. Anonymous says:

    Excellent!

  120. puligilla says:

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

  121. Anonymous says:

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

  122. Anonymous says:

    Agree this!

Comments are closed for this "Decorator Design Pattern" tutorial.