Monday, September 30, 2024

What is Factory method Design Pattern in Java with Example - Tutorial

Factory design pattern in Java one of the core design pattern which is used heavily not only in JDK but also in various Open Source framework such as Spring, Struts and Apache along with decorator design pattern in Java. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method in Java. One of the best examples of factory pattern in Java is BorderFactory Class of Swing API.

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 design pattern is used to create objects or Class in Java and it provides loose coupling and high cohesion. 

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

Factory method pattern in Java with example


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?

Whenever we talk about object-oriented language it will base upon some concept like abstraction, polymorphism, etc and that encapsulation and delegation are important concepts any design will be called good if tasks are delegated to a different object and some kind of encapsulation is there.

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. 

The factory methods are typically implemented as virtual methods, so this pattern is also referred to as the “Virtual Constructor”. These methods create the objects of the products or target classes. You can further see these Java design pattern online courses to learn more about classical Object-oriented design pattern and their implementation in ava. 

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:

factory design patter in java tutorial with exampleFactory pattern in Java is heavily used everywhere including JDK, open source library and other frameworks. In following are main advantages of using Factory 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.

3) Another benefit of using Factory design pattern in Java is that it encourages consistency in Code since every time object is created using Factory rather than using different constructor at different client side.

4) Code written using Factory design pattern in Java is also easy to debug and troubleshoot because you have a centralized method for object creation and every client is getting object from same place.


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());

2. Since the static factory method has a return type as Interface, it allows you to replace implementation with a better performance version in a newer release.

3. Another advantage of static factory method patterns is that they can cache frequently used objects and eliminate duplicate object creation. Boolean.valueOf() method is a good example that caches true and false boolean values.

4. Factory method pattern is also recommended by Joshua Bloch in Effective Java.

5 Factory method pattern offers an alternative way of creating objects.

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.

Other Java Design Patterns tutorials you may like
  • 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)     


21 comments :

Anonymous said...

I have a question about design patterns Please tell me which one pattern I apply to solve this problem...

Q-We are creating an application for shape drawing. We have to support multiple shapes
like circle, rectangle, square, polygon etc. These shapes may are related to each other
like square is a type of rectangle where rectangle is also kind of polygon. We want to
have an option of theme as well in our application. This theme option will allow us to
draw shapes with some filled content like marble theme will allow us to create shapes
filled with marbles where flower theme will allow us to create shape filled with flowers.
By default user can create shapes with borders with no fill. In order to provide
convenience to user we have an imaginary shape like Frame. The idea to introduce
frame is to hold different shapes so user can move or apply effects in one go.
Your task is to create classes / interfaces for given problem

Anonymous said...

I think your problem require multiple design patterns to solve that let's see how can we address your problem one by one:
Your Class hierarchy itself ask for base class or interface shape with method paint() to render itself and then subclass would be Rectangle and circle etc. You can use Factory pattern to encapsulate your Shape creation code
and could have method like
Shape createShape(Strin shape) which can serve to return default Shape with border and no fill.
Now on theme part you can define an interface called theme and various theme like MarbleTheme or RoseTheme will just be there concrete implementation. Now Apply composition and create a field called "theme" of interface type Theme inside Shape Class and provide setter method for theme. This way you can set any theme you want for your shape and your code will follow Open Closed principle where Themes are open for extension. Now just apply theme while drawing your Shape inside paint method if no theme than draw blank space. if you want theme to be update at runtime then call update() method from setTheme() and repaint shape. Now just like in Swing Frame can contain different components you can Have a Container Frame class which may support layout and calls different components paint method to render them.

Anonymous said...

Nice Explanation. I read lot of material about the factory design pattern but it is the best to understand clearly.

Anonymous said...

Can you please share some examples of factory design pattern from Core Java library ?

Anonymous said...

List of design patterns used in Java SE

http://vedashankar.blogspot.co.nz/2012/09/design-patterns-usage-in-java-se-and.html

Anonymous said...

Can someone tell me which design pattern to be used for converting a number to words. Like 123 as One Hundred and Twenty three

Unknown said...

i have to solve a problem , and the problem is:
problem: i have a lots of methods, and i want to give access of my methods to different people, but not of all. means suppose first person needs only 2 of my methods, second needs 3 of any methods, third needs only 5 of methods and so on.
i just want to make such kind of design. using different classes i don't think its a good idea. if i m using interface for all methods and then using class for required methods implementation then this case will require making class abstract.....means can't create object.... so suggest me any idea...

Jackob said...

I have a doubt regarding Factory design pattern, if I provide Factory method inside a separate class e.g. ConnectionFactory.createConnection(String url), which creates different types of connection based upon URL like HttpConnection for "http://", FileConnection for "file:///", SMTPConnection for "smtp://", do I need to make constructor of HttpConnection, FileConnection or SMTPConnection "private", so that no one can create instance of those class, without using Factory method?

If yes, then how will ConnectionFactory operate, until of-course its an static nested class, which is not the case.

If no, shouldn't it allow client to create instances using new() and by passing Factory method?

Please advise.

Anonymous said...

Essence of Factory Pattern is "programming for interface than implementation" , so the factory will only expose the interface name and not the implementing class name to the client.

Anonymous said...

Is there any difference between factory pattern and factory method pattern ?

Anonymous said...

In your main, you said:
Currency rupee = CurrencyFactory.createCurrency(country);
and you named the variable "rupee" even though the argument to main could have been "US". How do you handle naming variables in a mnemonic way using patterns?

Ranjith chandran, R said...

Hi - Your site is very informative - However I think you have given a "simple factory" example instead of real "factory-method pattern" - the code does not reflect the design pattern where "derived class is deciding what object to instantiate" - This example is very misleading and is causing tight coupling between various currency types and CurrencyFactory - and promoting violation of OCP ( on CurrencyFactory) and DRY ( using if-else-if) and loose coupling - benefits that "Factory method" is supposed to provide.

Unknown said...

isn't Map synchronizedMap = Collections.synchronizedMap(new HashMap()); a decorator pattern?

javin paul said...

Yes, you are right, it is the example of Decorator pattern.

Anonymous said...

Nice Explanation. I read lot of material about the factory design pattern but it is the best to understand clearly.

Unknown said...

hey.we are kindly working on a project and kindly please suggest some ideas..we have different set of json template rules and we want it to use it as a tool when a user validates a Json..so our project provides a tool..so what wil be the best and easiest way for the user to use this tool...simultaneously it opens a console and gives the validation result

Unknown said...

This example of factory method is misleading. where the subclass decides the type of object is created.

javin paul said...

Hello Nihalanshu, what do you mean by subclass decides the type of object is created?The whole purpose of factory pattern is to decouple clients from the classes they use i.e. allow them to create instance of a class without calling constructor. Can you clarify your point in more details please?

Anonymous said...

wonderful example code ... Thank you

Anonymous said...

spelling mistake above. 'Problem' is not spelled 'Problme'. HTH

Anonymous said...

best among all

Post a Comment