{"id":2168,"date":"2023-11-24T08:53:35","date_gmt":"2023-11-24T08:53:35","guid":{"rendered":"https:\/\/msgprogramator.sk\/design-patterns-java-decorator\/"},"modified":"2025-10-22T10:59:27","modified_gmt":"2025-10-22T10:59:27","slug":"java-decorator","status":"publish","type":"post","link":"https:\/\/msgprogramator.sk\/en\/java-decorator\/","title":{"rendered":"Java design pattern Decorator"},"content":{"rendered":"<p>Today we will take a look at another <strong>Java <\/strong><strong>design pattern<\/strong> from the <strong>structural patterns<\/strong> category &#8211; Decorator. Design patterns in this category deal with class structure such as <strong>inheritance<\/strong> and <strong>composition<\/strong>.<\/p>\n<h2>What is the Decorator design pattern?<\/h2>\n<p><strong>Decorator <\/strong> is a design pattern that is used to dynamically add (and remove) new responsibilities or features to existing objects without affecting the behaviour of other objects of the same class. Adding new functionality is also called decorating, hence the name of this design pattern.<\/p>\n<h2>What problem does the Decorator design pattern solve?<\/h2>\n<p>Decorator solves the problem of changing instances of classes without the need to create additional derived classes, because it attaches the new functionality to the object dynamically. Using this pattern can be much more efficient than creating subclasses because the behaviour of an object can be extended without defining an entirely new object. It is mainly used when we need to extend an object (Decorator does not extend the class).<\/p>\n<h2>Example of Decorator implementation in Java<\/h2>\n<p>We will now write a program that demonstrates the use of the <strong>Decorator<\/strong> design pattern to create decorated ice creams (= zmrzlina in Slovak) with various extra ingredients.<\/p>\n<p>The <strong>IZmrzlina<\/strong> interface defines a <em>vyrobZmrzlinu()<\/em> method that will be implemented by the various ice creams.<\/p>\n<p><strong><u>IZmrzlina.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic interface IZmrzlina {\n    public String vyrobZmrzlinu();\n}\n<\/code><\/pre>\n<p>The Zmrzlina class implements the <strong>IZmrzlina<\/strong> interface and provides a basic implementation of ice cream.<\/p>\n<p><strong><u>Zmrzlina.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class Zmrzlina implements IZmrzlina {\n    @Override\n    public String vyrobZmrzlinu() {\n        return &quot;Zmrzlina&quot;;\n    }\n}\n<\/code><\/pre>\n<p>The <strong>ZmrzlinaDecorator<\/strong> abstract class implements the <strong>IZmrzlina<\/strong> interface and contains a reference to the <strong>IZmrzlina<\/strong> instance to be decorated. This class returns the result of the <em>vyrobZmrzlinu()<\/em> method of the decorated ice cream.<\/p>\n<p><strong><u>ZmrzlinaDecorator.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\nabstract class ZmrzlinaDecorator implements IZmrzlina {\n    protected IZmrzlina upravenaZmrzlina;\n\n    public ZmrzlinaDecorator(IZmrzlina upravenaZmrzlina) {\n        this.upravenaZmrzlina = upravenaZmrzlina;\n    }\n\n    @Override\n    public String vyrobZmrzlinu() {\n        return upravenaZmrzlina.vyrobZmrzlinu();\n    }\n}\n<\/code><\/pre>\n<p>The <strong>CokoladaDecorator<\/strong> class is a particular decorator that adds chocolate syrup to ice cream. This class calls the <em> vyrobZmrzlinu() <\/em> method over the ice cream reference and coats it with chocolate syrup.<\/p>\n<p><strong><u>CokoladaDecorator.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class CokoladaDecorator extends ZmrzlinaDecorator {\n\n        public CokoladaDecorator(IZmrzlina upravenaZmrzlina) {\n            super(upravenaZmrzlina);\n        }\n\n        public String vyrobZmrzlinu() {\n            return upravenaZmrzlina.vyrobZmrzlinu() + pridajCokoladu();\n        }\n\n        private String pridajCokoladu() {\n            return &quot;, poliata cokoladovou polevou&quot;;\n        }\n}\n<\/code><\/pre>\n<p>The <strong>ArasidyDecorator<\/strong> class is another particular decorator that adds crushed peanuts to ice cream. Similar to the <strong> CokoladaDecorator,<\/strong>, this class calls the <em>vyrobZmrzlinu()<\/em> method over an ice cream reference and sprinkles it with crushed peanuts.<\/p>\n<p><strong><u>ArasidyDecorator.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">package designpatterns;\n\npublic class ArasidyDecorator extends ZmrzlinaDecorator {\n\n        public ArasidyDecorator(IZmrzlina upravenaZmrzlina) {\n            super(upravenaZmrzlina);\n        }\n\n        public String vyrobZmrzlinu() {\n            return upravenaZmrzlina.vyrobZmrzlinu() + pridajArasidy();\n        }\n\n        private String pridajArasidy() {\n            return &quot;, posypana drvenymi arasidami&quot;;\n        }\n}\n<\/code><\/pre>\n<p>In the <em>main()<\/em> method, we create a concrete ice cream object with a decorating sequence. Starting with the original ice cream (<strong>Zmrzlina<\/strong>), add first the chocolate syrup (<strong>CokoladaDecorator<\/strong>) and then the crushed peanuts (<strong>ArasidyDecorator<\/strong>).<\/p>\n<p><strong><u>Main.java<\/u><\/strong><\/p>\n<pre><code class=\"language-java\" data-line=\"\">import designpatterns.*;\n\npublic class Main {\n    public static void main(String[] args) {\n        IZmrzlina zmrzlina = new ArasidyDecorator(new CokoladaDecorator(new Zmrzlina()));\n        System.out.println(zmrzlina.vyrobZmrzlinu());\n    }\n}\n<\/code><\/pre>\n<p>The decorators can be combined in any order. This flexibility and dynamic change of instance behaviour at runtime is a fundamental advantage of the <strong>Decorator<\/strong> design pattern.<\/p>\n<figure id=\"attachment_1608\" aria-describedby=\"caption-attachment-1608\" style=\"width: 640px\" class=\"wp-caption alignnone\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-1608 size-large\" src=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/vystup-z-prikladu-1500-300-1024x205.webp\" alt=\"The decorators can be combined in any order. This flexibility and dynamic change of instance behaviour at runtime is a fundamental advantage of the Decorator design pattern.\" width=\"640\" height=\"128\"><figcaption id=\"caption-attachment-1608\" class=\"wp-caption-text\">Output from the Decorator design pattern example.<\/figcaption><\/figure>\n<h2>Conclusion<\/h2>\n<p>The Decorator design pattern is used when we need to add dynamic responsibility to an interface by wrapping the original code. If we used simple inheritance to add new functionality, all objects would inherit this functionality, even those that don&#8217;t need it. We can avoid this by using this pattern.<\/p>\n<p>We have prepared the files with the above example in the form of code that you can run directly in Java. Download the <a href=\"https:\/\/msgprogramator.sk\/wp-content\/uploads\/2023\/11\/Decorator.zip\">Java Decorator code here.<\/a><\/p>\n<p>Do you know the <a href=\"https:\/\/msgprogramator.sk\/java\/\">Java programming language<\/a>? If you&#8217;re looking for a job as a <a href=\"https:\/\/msg-life.sk\/en\/jobs\/java-programmer-senior\/\">Java developer<\/a>, check out our <a href=\"https:\/\/msg-life.sk\/en\/benefits\/\">employee benefits<\/a> and respond to our latest <a href=\"https:\/\/msg-life.sk\/en\/jobs\/\">job offers<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is Decorator design pattern and what is it used for? Read our new article and download the sample code.<\/p>\n","protected":false},"author":14,"featured_media":2038,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[57],"tags":[],"class_list":["post-2168","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java"],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2168","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/comments?post=2168"}],"version-history":[{"count":6,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2168\/revisions"}],"predecessor-version":[{"id":9327,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/posts\/2168\/revisions\/9327"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media\/2038"}],"wp:attachment":[{"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/media?parent=2168"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/categories?post=2168"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/msgprogramator.sk\/en\/wp-json\/wp\/v2\/tags?post=2168"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}