<p><strong>Factory pattern</strong> or <strong>Factory method Design Pattern</strong> is one of the most used the <strong><a href="https://dineshonjava.com/creational-design-patterns/">creational design pattern</a></strong>, according to this design pattern you creates an object with exposing the underlying logic to the client and assign new object to caller using a common interface or abstract class.</p>
<p>In <strong>Factory pattern</strong>, we hides actual logic of implementation detail of an object how create it and which class to instantiate it. So client shouldn&#8217;t worry about creating, managing and destroying object, factory pattern take responsibility of these tasks. Factory pattern is one of the most used design patterns in Java.</p>
<h2>Factory Method Design Pattern</h2>
<div style="text-align: left;">
<blockquote><p><em><strong>According to the Gang of Four:</strong></em></p>
<div style="text-align: left;">&#8220;Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.&#8221;</div>
</blockquote>
</div>
<p>As traditionally, we all are aware how to create the using new keyword in java as below:</p>
<pre class="highlight">Account account = new Account(); 
</pre>
<p>But this way is not suitable for sometime, because it is hard coded way to create an object, also it is not a best practice to create an object if object might be changed according to the nature of the program. Here creation design pattern provide the flexibility to create an according to the nature of program.</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>UML Class Diagram for Factory Design Pattern</h2>
<p>Let&#8217;s see the following UML class diagram for the Factory Design Pattern.</p>
<p><img class="aligncenter size-full wp-image-3662" src="https://dineshonjava.com/wp-content/uploads/2017/12/Factory-Design-Pattern.png" alt="Factory Method Design Pattern " width="519" height="323" /></p>
<p>Let&#8217;s see the classes and objects participating in this pattern are:</p>
<p><strong>Product (Account)</strong></p>
<ul>
<li>This is an interface and it defines the interface of objects the factory method creates</li>
</ul>
<p><strong>ConcreteProduct (SavingAccount, CurrentAccount)</strong></p>
<ul>
<li>These are concrete classes and it implements the Product interface.</li>
</ul>
<p><strong>Creator (AccountFactory)</strong></p>
<ul>
<li>It is a Factory class or Factory interface and it declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.</li>
<li>It may call the factory method to create a Product object.</li>
</ul>
<p><strong>ConcreteCreator (AccountFactoryImpl)</strong></p>
<ul>
<li>If Creator is an interface or abstract class then it overrides the factory method to return an instance of a ConcreteProduct.</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/abstract-factory-design-pattern/" href="https://dineshonjava.com/abstract-factory-design-pattern/">Abstract Factory 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/structural-design-patterns/" href="https://dineshonjava.com/structural-design-patterns/">Structural 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>Benefits of Factory Method Design Pattern</h2>
<p>Let&#8217;s see the following pros of the Factory Method Design Pattern:</p>
<ul>
<li>Factory Method Pattern promotes the loose coupling between the collaborating components or classes by using interfaces rather than bind application-specific classes into the application code.</li>
<li>Using this pattern, you can get any implementation of an object of classes, that implement interface, at run time.</li>
<li>Object life cycle managed by the factory implemented by this pattern.</li>
</ul>
<h2>Disadvantages of Factory Method Design Pattern</h2>
<p>Let&#8217;s see the following cons of the Factory Method Design Pattern:</p>
<ul>
<li>The only disadvantage with the factory pattern may introduce unnecessary complication into the code.</li>
<li>Makes code more difficult to read as all of your code is behind an abstraction that may in turn hide abstractions.</li>
<li>In Factory Method pattern, the factory used for creating the objects is bound with the client code, i.e., it is difficult to use a different factory for creating objects.</li>
</ul>
<h2>Applicability of Factory Pattern</h2>
<p>There are following cases where we can apply the Factory method pattern in the application.</p>
<ul>
<li>Factory pattern remove the over burden from the developer to create and manage the objects.</li>
<li>This pattern remove tight coupling between collaboration components because a component doesn&#8217;t know what sub-classes will be required to create.</li>
<li>Avoid hard code to create an object of the class.</li>
</ul>
<h2>Example of the Factory Design Pattern</h2>
<p>There are following implementations based on this pattern.</p>
<ul>
<li>BeanFactory in the Spring Framework</li>
<li>SessionFactory in the Hibernate Framework</li>
</ul>
<h2>Sample Implementation of Factory Design Pattern</h2>
<p>Suppose you have set of classes i.e. <em><strong>SavingAccount</strong></em>, and <em><strong>CurrentAccount</strong></em> which extends a common super class or interface i.e. <em><strong>Account</strong></em>. You have one more class, i.e. a Factory class, define with a method with taking one or more arguments. This method is know as factory method and this factory method has return type a Super class or interface as define Account so that it provide you loose coupling, you can program to interface rather than implementation. So according to passed arguments in the factory method, decides on which sub class to instantiate. This factory method will have the super class as its return type.</p>
<h3>Step 1: Let&#8217;s create an interface.</h3>
<p><strong>Account.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.creational.factory; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public interface Account { 
	 
	void accountType(); 
} 
 
</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.creational.factory; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class SavingAccount implements Account { 
 
	@Override 
	public void accountType() { 
		System.out.println("SAVING ACCOUNT"); 
	} 
 
} 
 
</pre>
<p><strong>CurrentAccount.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.creational.factory; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class CurrentAccount implements Account { 
 
	@Override 
	public void accountType() { 
		System.out.println("CURRENT ACCOUNT"); 
	} 
 
} 
 
</pre>
<h3>Step 3 : Create a Factory to generate object of concrete class based on given information.</h3>
<p><strong>AccountFactory.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.creational.factory; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class AccountFactory { 
	 
	final String CURRENT_ACCOUNT = "CURRENT"; 
	final String SAVING_ACCOUNT = "SAVING"; 
	//use getAccount method to get object of type Account 
	//It is factory method for object of type Account 
 public Account getAccount(String accountType){ 
 	if(CURRENT_ACCOUNT.equals(accountType)) { 
 		return new CurrentAccount(); 
 	}else if(SAVING_ACCOUNT.equals(accountType)){ 
 		return new SavingAccount(); 
 	} 
 	return null; 
 } 
} 
 
</pre>
<h3>Step 4 : Let&#8217;s use this Factory to get object of concrete class by passing an information such as type.</h3>
<p><strong>FactoryPatternDemo.java</strong></p>
<pre class="highlight">/** 
 * 
 */ 
package com.doj.patterns.creational.factory; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class FactoryPatternDemo { 
 
	/** 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		AccountFactory accountFactory = new AccountFactory(); 
		//get an object of SavingAccount and call its accountType() method. 
		Account savingAccount = accountFactory.getAccount("SAVING"); 
		//call accountType method of SavingAccount 
		savingAccount.accountType(); 
		//get an object of CurrentAccount and call its accountType() method. 
		Account currentAccount = accountFactory.getAccount("CURRENT"); 
		//call accountType method of CurrentAccount 
		currentAccount.accountType(); 
	} 
 
} 
 
</pre>
<h3>Step 5 : Let&#8217;s run this demo class and verify the output.</h3>
<pre class="highlight">SAVING ACCOUNT 
CURRENT ACCOUNT 
 
</pre>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/abstract-factory-design-pattern/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/builder-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: '3659'});
});
</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…