<p>The <strong>Decorator Design Pattern</strong> is a special type of pattern one of the <strong><a href="https://dineshonjava.com/structural-design-patterns/">Structural Patterns</a></strong>, that allows you to add and removing behaviours to an individual object at the run-time dynamically or statically without changing the existing behaviour of other associated objects from the same class.</p>
<p>In software engineering, the common intent of all GOF <strong><a href="https://dineshonjava.com/structural-design-patterns/">structural patterns</a></strong> is to simplify the complex relationship between objects and classes in a flexible in the enterprise application. This Decorator pattern does this without violating the <strong>Single Responsibility Principle of the SOLID</strong> principle of object-oriented programming.</p>
<h2>Decorator Design Pattern</h2>
<div style="text-align: left;">
<blockquote><p><strong>According to the Gang of Four:</strong></p>
<div style="text-align: left;">Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.</div>
</blockquote>
</div>
<p>This design pattern uses the compositions over the inheritance for objects associations, it allows you to divide the functionality into different concrete classes with a unique area of concern.</p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px 16px 16px 16px;">
<h2 dir="ltr">Spring 5 Design Pattern Book</h2>
<div dir="ltr" style="color: #20124d; font-family: 'calibri' , sans-serif; font-size: 13pt; text-align: justify;">You could purchase my <strong>Spring 5 book</strong> that is with title name &#8220;<strong>Spring 5 Design Patterns</strong>&#8220;. This book is available on the <a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?ie=UTF8&;qid=1507925340&;sr=8-1&;keywords=spring+5+design+pattern" target="_blank" rel="noopener"><strong>Amazon</strong></a> and <a href="https://www.packtpub.com/application-development/spring-5-design-patterns" target="_blank" rel="noopener"><strong>Packt</strong></a> publisher website. Learn various <strong>design patterns</strong> and <strong>best practices</strong> in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- &#8220;<strong>AUTHDIS40</strong>&#8220;.</div>
<div dir="ltr"></div>
<div dir="ltr"><a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?s=books&;ie=UTF8&;qid=1512607966&;sr=1-1&;keywords=dinesh+rajput" target="_blank" rel="noopener"><img class="aligncenter wp-image-3053 size-medium" title="Spring-5-Design-Pattern" src="https://dineshonjava.com/wp-content/uploads/2013/03/Spring-5-design-pattern-243x300.jpg" width="243" height="300" /></a></div>
</div>
<h2>Applicability</h2>
<p>There is a requirement of the business or might be some future planning for the product to extend behaviour by adding the new functionality to an object, to achieving it you could use inheritance to extend the behaviour of an object. But inheritance should be done at compile time and is also available for other instances of that class. And because of code modification required in case of inheritance, which is a violation of the <strong>Open Closed Principle</strong>. Instead, to avoid this violation of SOLID principle, you can attach new responsibility to an object dynamically. This is exactly the situation, the decorator design pattern comes into the picture and addresses this issue in a very flexible way.</p>
<div style="text-align: left;">
<blockquote><p><strong>also read:</strong></p>
<ul style="text-align: left;">
<li><a title="https://dineshonjava.com/adapter-design-pattern/" href="https://dineshonjava.com/adapter-design-pattern/">Adapter Design Pattern</a></li>
<li><a title="https://dineshonjava.com/bridge-design-patterns/" href="https://dineshonjava.com/bridge-design-patterns/">Bridge Design Pattern</a></li>
<li><a title="https://dineshonjava.com/facade-design-pattern/" href="https://dineshonjava.com/facade-design-pattern/">Facade Design Pattern</a></li>
<li><a title="https://dineshonjava.com/proxy-pattern-design-patterns-java/" href="https://dineshonjava.com/proxy-pattern-design-patterns-java/">Proxy Design Pattern</a></li>
<li><a title="https://dineshonjava.com/builder-design-pattern/" href="https://dineshonjava.com/builder-design-pattern/">Builder Design Pattern</a></li>
<li><a title="https://dineshonjava.com/flyweight-pattern-design-patterns-java/" href="https://dineshonjava.com/flyweight-pattern-design-patterns-java/">Flyweight Design Pattern</a></li>
<li><a title="https://dineshonjava.com/creational-design-patterns/" href="https://dineshonjava.com/creational-design-patterns//">Creational GoF Design Patterns</a></li>
<li><a title="https://dineshonjava.com/behavioral-design-pattern/" href="https://dineshonjava.com/behavioral-design-pattern/">Behavioral GoF Design Patterns</a></li>
</ul>
</blockquote>
</div>
<h2>UML Structure for Decorator Design Pattern</h2>
<p>Let&#8217;s see the following figure that illustrates the classes and objects participating in this pattern are:</p>
<p><img class="aligncenter size-full wp-image-3698" src="https://dineshonjava.com/wp-content/uploads/2017/12/decorator.gif" alt="Decorator Design pattern" width="431" height="356" /><br />
<strong>Component (Account)</strong></p>
<ul>
<li>It is an interface for objects that can have responsibilities added to them dynamically.</li>
</ul>
<p><strong>ConcreteComponent (SavingAccount)</strong></p>
<ul>
<li>It is a concrete class of component interface and it defines an object to which additional responsibilities can be attached.</li>
</ul>
<p><strong>Decorator (AccountDecorator)</strong></p>
<ul>
<li>It has a reference to a Component object and defines an interface that conforms to Component&#8217;s interface.</li>
</ul>
<p><strong>ConcreteDecorator (SeniorCitizen, Privilege)</strong></p>
<ul>
<li>It is a concrete implementation of Decorator and it adds responsibilities to the component.</li>
</ul>
<h2>Pros of the Decorator Pattern</h2>
<p>There are following pros of using this decorator pattern.</p>
<ul>
<li>This pattern allows you to extend functionality dynamically and statically without altering the structure of existing objects.</li>
<li>By using this pattern, you could add a new responsibility to an object dynamically.</li>
<li>Decorator pattern is also known as Wrapper.</li>
<li>It uses the compositions for object relationships to maintain SOLID principles.</li>
<li>By using this pattern we can simplify coding by writing new classes for every new specific functionality rather changes into the existing code of your application.</li>
</ul>
<h2>Cons of the Decorator Pattern</h2>
<p>There are following pros of using this decorator pattern.</p>
<ul>
<li>Decorator pattern can result in many small objects in our design, and overuse can be complex</li>
<li>It can cause issues if the client relies heavily on the components concrete type</li>
<li>Decorators can complicate the process of instantiating the component because you not only have to instantiate the component but wrap it in a number of decorators</li>
</ul>
<h2>Real Case Study for the Decorator Design Pattern</h2>
<p>Let&#8217;s look into the following example how to implement this design pattern into a real case study.</p>
<p>Consider a <strong>Bank</strong> offers multiple accounts with different benefits to the customers, it divided the customers into three categories as like <strong>Senior Citizen</strong>, <strong>Privilege</strong> and <strong>Young</strong>. Bank launched a scheme to the Saving account for Senior citizen as bank provides a medical insurance of up to $1,000 for Senior Citizen if they open saving account in this bank, similarly bank also provides a scheme to the privilege customers as an accident insurance of up to $1,600 and an overdraft facility of $84. There is no scheme for the Young.</p>
<p>To address the new requirement, we can add new subclasses of <em><strong>SavingAccount</strong></em>, one each to represent a saving account with additional benefits as decoration, and this is how our design looks like now. Clearly, this design is flawed, but this is an ideal use case for the decorator pattern. Decorator design pattern allows you to add run time dynamically behaviour, in this case, I will create an abstract <em><strong>AccountDecorator</strong> </em>class to implement Account. And furthermore, I will create the <em><strong>SeniorCitizen</strong> </em>and Privilege class extend and <em><strong>AccountDecorator</strong> </em>because Young does not have any extra benefits, so class <strong><em>SavingClass</em> </strong>does not extend <strong><em>AccountDecorator</em></strong>. This is how the design will be.</p>
<p><img class="aligncenter size-full wp-image-3699" src="https://dineshonjava.com/wp-content/uploads/2017/12/design-with-decorator.png" alt="design with decorator pattern" width="459" height="200" /></p>
<p>In the figure above, it follows the Decorator Design Pattern by creating <em><strong>AccountDecorator</strong> </em>as a Decorator in this pattern, and focus on the important thing to observe the relationship between <em><strong>Account</strong> </em>and <em><strong>AccountDecorator</strong></em>. This relationship as below:</p>
<ul>
<li><strong>IS-A relationship</strong> between the <em><strong>AccountDecorator</strong> </em>and <em><strong>Account</strong></em>, i.e. inheritance for the correct type.</li>
<li><strong>HAS-A relationship</strong> between the <em><strong>AccountDecorator</strong> </em>and <em><strong>Account</strong></em>, the i.e. composition in order to add new behaviour without changing existing code.</li>
</ul>
<h2>Sample Implementation of the Decorator Design Pattern</h2>
<p>Let&#8217;s look into the following sample codes to demonstrate the Decorator Design Pattern.</p>
<h3>Step 1: Create an interface.</h3>
<p><strong>Account.java</strong></p>
<pre class="highlight">package com.doj.patterns.structural.decorator;

public interface Account {
	String getTotalBenefits();
}

</pre>
<h3>Step 2: Create concrete classes implementing the same interface.</h3>
<p><strong>SavingAccount.java</strong></p>
<pre class="highlight">package com.doj.patterns.structural.decorator;

/**
 * @author Dinesh.Rajput
 *
 */
public class SavingAccount implements Account {

	@Override
	public String getTotalBenefits() {
		return "This account has 4% interest rate with per day $5000 withdrwal limit";
	}

}

</pre>
<p><strong>CurrentAccount.java</strong></p>
<pre class="highlight">package com.doj.patterns.structural.decorator;

/**
 * @author Dinesh.Rajput
 *
 */
public class CurrentAccount implements Account{
	
	@Override
	public String getTotalBenefits() {
		return "There is no withdrwal limit for current account";
	}

}

</pre>
<h3>Step 3: Create abstract decorator class implementing the <em>Account</em> interface.</h3>
<p><strong>AccountDecorator.java</strong></p>
<pre class="highlight">package com.doj.patterns.structural.decorator;

/**
 * @author Dinesh.Rajput
 *
 */
public abstract class AccountDecorator implements Account{
	
	abstract String applyOtherBenefits();

}

</pre>
<h3>Step 4: Create a concrete decorator class extending the <em>AccountDecorator</em> class.</h3>
<p><strong>Privilege.java</strong></p>
<pre class="highlight">package com.doj.patterns.structural.decorator;

/**
 * @author Dinesh.Rajput
 *
 */
public class Privilege extends AccountDecorator {
	
	Account account;
	
	public Privilege(Account account) {
		super();
		this.account = account;
	}

	@Override
	public String getTotalBenefits() {
		return account.getTotalBenefits() + " other benefits are "+applyOtherBenefits();
	}

	@Override
	String applyOtherBenefits() {
		return " an accident insurance of up to $1,600 and an overdraft facility of $84";
	}

}

</pre>
<h3>Step 5: Let&#8217;s create a demo class and use the <em>Privilege</em> to decorate <em>Account</em> objects.</h3>
<p><strong>DecoratorPatternMain.java</strong></p>
<pre class="highlight">package com.doj.patterns.structural.decorator;

/**
 * @author Dinesh.Rajput
 *
 */
public class DecoratorPatternMain {

	public static void main(String[] args) {
		/*Saving account with no decoration*/
		Account basicSavingAccount = new SavingAccount();
		System.out.println(basicSavingAccount.getTotalBenefits());
		
		/*Saving account with senior citizen benefits decoration*/
		Account seniorCitizenSavingAccount = new SavingAccount();
		seniorCitizenSavingAccount = new SeniorCitizen(seniorCitizenSavingAccount);
		System.out.println(seniorCitizenSavingAccount.getTotalBenefits());
		
		/*Saving account with privilege decoration*/
		Account privilegeCitizenSavingAccount = new SavingAccount();
		privilegeCitizenSavingAccount = new Privilege(privilegeCitizenSavingAccount);
		System.out.println(privilegeCitizenSavingAccount.getTotalBenefits());
	}

}

</pre>
<h3>Step 6: Let&#8217;s run the above demo class and verify the output.</h3>
<pre class="highlight">This account has 4% interest rate with per day $5000 withdrwal limit
This account has 4% interest rate with per day $5000 withdrwal limit other benefits are an medical insurance of up to $1,000 for Senior Citizen
This account has 4% interest rate with per day $5000 withdrwal limit other benefits are an accident insurance of up to $1,600 and an overdraft facility of $84

</pre>
<h2>Examples of the Decorator Design Pattern in Java API</h2>
<p>There are following implementations of this pattern.</p>
<ul>
<li>java.io.BufferedReader;</li>
<li>java.io.FileReader;</li>
<li>java.io.Reader;</li>
</ul>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/bridge-design-patterns/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/facade-design-pattern/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '3697'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…