What is Factory method Design Pattern in Java with Example
In this Design pattern tutorial we will see What is Factory method design pattern in Java, what are main advantages of factory pattern in Java , code example of Factory design pattern and what problem Factory pattern solves in Java or when to use Factory design pattern.
This article is in continuation of my design pattern article as 10 OOPS and SOLID design principles java programmer should know and How to use Observer pattern in Java
What is static factory method or factory design pattern?
Factory pattern encapsulate object creation logic which makes it easy to change it later when you change how object gets created or you can even introduce new object with just change in one class.
In GOF pattern list Factory pattern is listed as Creation design pattern. Factory should be an interface and clients first either creates factory or get factory which later used to create objects.
Example of a static factory method in JDK
Best Example of Factory method design pattern is valueOf() method which is there in String and wrapper classes like Integer and Boolean and used for type conversion i.e. from converting String to Integer or String to double in java..
Some more examples of factory method design pattern from JDK is :
valueOf() method which returns object created by factory equivalent to value of parameter passed.
getInstance() method which creates instance of Singleton class.
newInstance() method which is used to create and return new instance from factory method every time called.
getType() and newType() equivalent of getInstance() and newInstance() factory method but used when factory method resides in separate class.
Here is a nice diagram of Factory method design pattern with a code example for quick review, we will see another example in next few paragraph but this will give you a quick overview of what is factory pattern and how it is used to create objects
The diagram provides a comprehensive view of the Factory Method Pattern, you can see that:
- The abstract Creator class with its factory method (CreateProduct) and an operation that uses it (AnOperation).
- The concrete implementation (ConcreteCreator) that overrides the factory method.
- The Product interface with its DoStuff method.
- The ConcreteProduct that implements the Product interface.
The code example also illustrates how the Creator class is structured with an abstract factory method and how it’s used in the AnOperation method. It also shows how the ConcreteCreator implements the factory method to return a specific ConcreteProduct.
What Problem is solved by Factory method Pattern in Java?
Some time our application or framework will not know that what kind of object it has to create at run-time it knows only the interface or abstract class and as we know we can not create an object of interface or abstract class so the main problem is framework knows when it has to create but don’t know what kind of object.
Whenever we create an object using new() we violate the principle of programming for interface rather than implementation which eventually results in inflexible code and is difficult to change in maintenance.
By using the Factory design pattern in Java we get rid of this problem.
Another problem we can face is class needs to contain objects of other classes or class hierarchies within it; this can be very easily achieved by just using the new keyword and the class constructor.
The problem with this approach is that it is a very hard-coded approach to create objects as this creates a dependency between the two classes.
So factory pattern solves this problem very easily by model an interface for creating an object which at creation time can let its subclasses decide which class to instantiate, Factory Pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code.
When to use the Factory design pattern in Java
- Static Factory methods are common in frameworks where library code needs to create objects of types which may be sub classed by applications using the framework.
- Some or all concrete products can be created in multiple ways, or we want to leave open the option that in the future there may be new ways to create the concrete product.
- Factory method is used when Products don’t need to know how they are created.
- We can use factory pattern where we have to create an object of any one of sub-classes depending on the data provided
Code Example of Factory Design Pattern in Java:
Let’s see an example of how factory pattern is implemented in Code.
We have requirement to create multiple currency e.g. INR, SGD, USD and code should be extensible to accommodate new Currency as well.
Here we have made Currency as interface and all currency would be concrete implementation of Currency interface.
Factory class will create Currency based upon country and return concrete implementation which will be stored in interface type. This makes code dynamic and extensible.
Here is complete code example of Factory pattern in Java:
interface Currency {
String getSymbol();
}
// Concrete Rupee Class code
class Rupee implements Currency {
@Override
public String getSymbol() {
return “Rs”;
}
}
// Concrete SGD class Code
class SGDDollar implements Currency {
@Override
public String getSymbol() {
return “SGD”;
}
}
// Concrete US Dollar code
class USDollar implements Currency {
@Override
public String getSymbol() {
return “USD”;
}
}
// Factroy Class code
class CurrencyFactory {
public static Currency createCurrency (String country) {
if (country. equalsIgnoreCase (“India”)){
return new Rupee();
}else if(country. equalsIgnoreCase (“Singapore”)){
return new SGDDollar();
}else if(country. equalsIgnoreCase (“US”)){
return new USDollar();
}
throw new IllegalArgumentException(“No such currency”);
}
}
// Factory client code
public class Factory {
public static void main(String args[]) {
String country = args[0];
Currency rupee = CurrencyFactory.createCurrency(country);
System.out.println(rupee.getSymbol());
}
}
Advantage of Factory method Pattern in Java:
1) Factory method design pattern decouples the calling class from the target class, which result in less coupled and highly cohesive code?
For example, JDBC is a good example for this pattern; application code doesn’t need to know what database it will be used with, so it doesn’t know what database-specific driver classes it should use.
Instead, it uses factory methods to get Connections, Statements, and other objects to work with. Which gives you flexibility to change your back-end database without changing your DAO layer in case you are using ANSI SQL features and not coded on DBMS specific feature?
2) Factory pattern in Java enables the subclasses to provide extended version of an object, because creating an object inside factory is more flexible than creating an object directly in the client.
Since client is working on interface level any time you can enhance the implementation and return from Factory.
Some more advantages of factory method design pattern is:
1. Static factory method used in factory design pattern enforces use of Interface than implementation which itself a good practice. for example:
Map synchronizedMap = Collections.synchronizedMap(new HashMap());
6. Factory patterns can also be used to hide information related to the creation of objects.
That’s all on the Factory design pattern in Java for now. This is one of the most used patterns in the Java library and different Java frameworks. In short, try to use Factory pattern whenever you see an opportunity to encapsulate object creation code and see the chance of creating a different object in near future.
- 5 Free Courses to learn Object Oriented Programming (courses)
- How to design a Vending Machine in Java? (questions)
- How to implement a Decorator design pattern in Java? (tutorial)
- How to use Factory method design pattern in Java? (tutorial)
- When to use Command Design Pattern in Java (example)
- 7 Best Courses to learn Design Pattern in Java (courses)
- How to create thread-safe Singleton in Java (example)
- Difference between Factory and Abstract Factory Pattern? (example)
- 7 Best Books to learn the Design Pattern in Java? (books)
- How to implement the Strategy Design Pattern in Java? (example)
- Difference between Factory and Dependency Injection Pattern? (answer)
- 18 Java Design Pattern Interview Questions with Answers (list)
- Difference between State and Strategy Design Pattern in Java? (answer)
- 20 System Design Interview Questions (list)
- 10 OOP Design Principle Every Java developer should learn (solid principle)
- 5 Free Courses to learn Data Structure and Algorithms (courses)
- 7 Books to learn System Design for Beginners (System design books)