<p>Flyweight pattern comes under the structural design pattern as like Adapter, Bridge, Decorator, Composition design patterns of the <strong><a href="https://dineshonjava.com/design-patterns_25/">23 GoF Design Patterns</a></strong>. This design pattern apply to improve the performance of application by reusing the existing similar kind of objects. This pattern store the similar kind of objects into cache to reuse, it creates new object when no matching object is found.</p>
<h2>The Flyweight Pattern</h2>
<div style="text-align: left;">
<blockquote><p><strong>According to the Gang of Four:</strong></p>
<div style="text-align: left;">Use sharing to support large numbers of fine-grained objects efficiently.</div>
</blockquote>
</div>
<p>Due to reuse of the number of objects in to application, Flyweight pattern reduce creation of the number of objects and it decreases memory usage and increase performance.</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 Pattern</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><strong>Pros of the Flyweight Pattern</strong></h2>
<p>Let&#8217;s see the following pros of the flyweight design pattern.</p>
<ul>
<li>Flyweight pattern improves the performance of application by reducing the number of objects.</li>
<li>This pattern reduces the amount of memory and storage devices required if the objects are persisted.</li>
</ul>
<h2><strong>Cons of the Flyweight Pattern</strong></h2>
<p>Let&#8217;s see the following cons of the flyweight design pattern.</p>
<ul>
<li>If your software does not have memory concerns flyweight design can lead to complicating the code with no performance gain.</li>
<li>It makes code complicated.</li>
</ul>
<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/decorator-design-pattern/" href="https://dineshonjava.com/decorator-design-pattern/">Decorator 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/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><strong>Applicability</strong></h2>
<p>Let&#8217;s see the following scenarios where we have to use the Flyweight pattern.</p>
<ul>
<li>When an application similar kind of objects in very large amount.</li>
<li>When you to reduce the storage cost of application.</li>
</ul>
<h2><strong>UML class diagram for Flyweight Design Pattern</strong></h2>
<p>Let&#8217;s see the following UML class diagram for the flyweight design pattern and it illustrates about some important components classes.</p>
<p><img class="aligncenter wp-image-3580 size-full" src="https://dineshonjava.com/wp-content/uploads/2017/12/flyweight.gif" alt="Flyweight Pattern Design Patterns in Java" width="467" height="289" /></p>
<h3>Flyweight</h3>
<p>It declares an interface through which flyweights can receive.</p>
<h3>ConcreteFlyweight</h3>
<p>It implements the Flyweight interface and it must be shareable.</p>
<h3>UnsharedConcreteFlyweight</h3>
<p>It is not all Flyweight subclasses need to be shared. The Flyweight interface enables sharing, but it doesn&#8217;t enforce it.</p>
<h3>FlyweightFactory</h3>
<p>It creates and manages flyweight objects.</p>
<h3>Client</h3>
<p>It maintains a reference to flyweight(s).</p>
<h2><strong>Sample Implementation for Flyweight Design Pattern</strong></h2>
<p>We are going to create a Employee interface and concrete class Manager implementing the Employee interface. A factory class EmployeeFactory is defined as a next step.</p>
<h3>Step 1: Create an interface.<br />
Employee.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.structural.flyweight; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public interface Employee { 
	 
	void work(); 
} 
 
</pre>
<h3>Step 2: Create concrete Manager class implementing the Employee interface.<br />
Manager.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.structural.flyweight; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class Manager implements Employee { 
	 
	private String department; 
	private double salary; 
	 
		public Manager(String department) { 
		super(); 
		this.department = department; 
	} 
 
 
	public String getDepartment() { 
		return department; 
	} 
 
 
	public void setDepartment(String department) { 
		this.department = department; 
	} 
 
 
	public double getSalary() { 
		return salary; 
	} 
 
 
	public void setSalary(double salary) { 
		this.salary = salary; 
	} 
 
 
	@Override 
	public void work() { 
		System.out.println("Manager of Department: "+department+" is taking salary: "+salary); 
	} 
 
} 
 
</pre>
<h3>Step 3: Create a factory EmployeeFactory to generate object of concrete class Manager based on given information.<br />
EmployeeFactory.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.structural.flyweight; 
 
import java.util.HashMap; 
import java.util.Map; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class EmployeeFactory { 
	private static final Map<;String, Employee>; managerMap = new HashMap<;>;(); 
 
	public static Employee getManager(String department) { 
		Manager manager = (Manager)managerMap.get(department); 
		 
		if(manager == null) { 
			manager = new Manager(department); 
			managerMap.put(department, manager); 
			System.out.println("Creating manager of department : " + department); 
		} 
		return manager; 
	} 
} 
 
</pre>
<h3>Step 4: Use the factory to get object of concrete class by passing an information such as department.<br />
FlyweightPatternDemo.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.structural.flyweight; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class FlyweightPatternDemo { 
	 
	 private static final String departments[] = { "IT", "ME", "EE", "CO", "PWD", "NR", "ST", "IAS"}; 
	 
	/** 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		for(int i=0; i <; 8; ++i) { 
			Manager manager = (Manager)EmployeeFactory.getManager(getRandomDepartment()); 
			manager.setSalary(getRandomSalary()); 
			manager.work(); 
		} 
	} 
	private static String getRandomDepartment() { 
		return departments[(int)(Math.random()*departments.length)]; 
	} 
	 
	private static double getRandomSalary() { 
		return (double)(Math.random()*100000); 
	} 
} 
 
</pre>
<h3>Step 5: Let&#8217;s run this demo class and verify the output.</h3>
<pre class="highlight">Creating manager of department : PWD 
Manager of Department: PWD is taking salary: 37743.55396460834 
Creating manager of department : IAS 
Manager of Department: IAS is taking salary: 45169.53270870482 
Creating manager of department : IT 
Manager of Department: IT is taking salary: 44540.66001403507 
Creating manager of department : ME 
Manager of Department: ME is taking salary: 79617.26799730789 
Creating manager of department : NR 
Manager of Department: NR is taking salary: 48541.33901789731 
Manager of Department: IT is taking salary: 45679.588691403296 
Creating manager of department : EE 
Manager of Department: EE is taking salary: 20382.416449759898 
Manager of Department: IT is taking salary: 27847.203390300823 
 
</pre>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/composite-pattern-design-patterns-java/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/proxy-pattern-design-patterns-java/">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: '3579'});
});
</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…