Design Pattern

Factory Method Design Pattern – Creational Patterns

Factory pattern or Factory method Design Pattern is one of the most used the creational design pattern, 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.

In Factory pattern, we hides actual logic of implementation detail of an object how create it and which class to instantiate it. So client shouldn’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.

Factory Method Design Pattern

According to the Gang of Four:

“Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.”

As traditionally, we all are aware how to create the using new keyword in java as below:

Account account = new Account();

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.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Patterns“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.

UML Class Diagram for Factory Design Pattern

Let’s see the following UML class diagram for the Factory Design Pattern.

Let’s see the classes and objects participating in this pattern are:

Product (Account)

  • This is an interface and it defines the interface of objects the factory method creates

ConcreteProduct (SavingAccount, CurrentAccount)

  • These are concrete classes and it implements the Product interface.

Creator (AccountFactory)

  • 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.
  • It may call the factory method to create a Product object.

ConcreteCreator (AccountFactoryImpl)

  • If Creator is an interface or abstract class then it overrides the factory method to return an instance of a ConcreteProduct.

Benefits of Factory Method Design Pattern

Let’s see the following pros of the Factory Method Design Pattern:

  • 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.
  • Using this pattern, you can get any implementation of an object of classes, that implement interface, at run time.
  • Object life cycle managed by the factory implemented by this pattern.

Disadvantages of Factory Method Design Pattern

Let’s see the following cons of the Factory Method Design Pattern:

  • The only disadvantage with the factory pattern may introduce unnecessary complication into the code.
  • Makes code more difficult to read as all of your code is behind an abstraction that may in turn hide abstractions.
  • 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.

Applicability of Factory Pattern

There are following cases where we can apply the Factory method pattern in the application.

  • Factory pattern remove the over burden from the developer to create and manage the objects.
  • This pattern remove tight coupling between collaboration components because a component doesn’t know what sub-classes will be required to create.
  • Avoid hard code to create an object of the class.

Example of the Factory Design Pattern

There are following implementations based on this pattern.

  • BeanFactory in the Spring Framework
  • SessionFactory in the Hibernate Framework

Sample Implementation of Factory Design Pattern

Suppose you have set of classes i.e. SavingAccount, and CurrentAccount which extends a common super class or interface i.e. Account. 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.

Step 1: Let’s create an interface.

Account.java

/**
 * 
 */
package com.doj.patterns.creational.factory;

/**
 * @author Dinesh.Rajput
 *
 */
public interface Account {
	
	void accountType();
}

Step 2 : Create concrete classes implementing the same interface.

SavingAccount.java

/**
 * 
 */
package com.doj.patterns.creational.factory;

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

	@Override
	public void accountType() {
		System.out.println("SAVING ACCOUNT");
	}

}

CurrentAccount.java

/**
 * 
 */
package com.doj.patterns.creational.factory;

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

	@Override
	public void accountType() {
		System.out.println("CURRENT ACCOUNT");
	}

}

Step 3 : Create a Factory to generate object of concrete class based on given information.

AccountFactory.java

/**
 * 
 */
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;  
    }  
}

Step 4 : Let’s use this Factory to get object of concrete class by passing an information such as type.

FactoryPatternDemo.java

/**
 * 
 */
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();
	}

}

Step 5 : Let’s run this demo class and verify the output.

SAVING ACCOUNT
CURRENT ACCOUNT

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago