Saturday 4 May 2013

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 patter in java tutorial with exampleFactory 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 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.

Problem which is solved by Factory method Pattern in Java

Whenever we talk about object oriented language it will based upon some concept like abstraction, polymorphism etc and on that encapsulation and delegation are important concept any design will be called good if task are delegated to 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 object of interface or abstract class so main problem is frame work knows when it has to create but don’t know what kind of object.
Whenever we create object using new() we violate principle of programming for interface rather than implementation which eventually result in inflexible code and difficult to change in maintenance. By using 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 dependency between the two classes.
So factory pattern solve 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.

When to use 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:

       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";
       }

       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");
       }
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 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?
E.g.: 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 static factory method have return type as Interface, it allows you to replace implementation with better performance version in newer release.
3. Another advantage of static factory method pattern is that they can cache frequently used object and eliminate duplicate object creation. Boolean.valueOf() method is good example which caches true and false boolean value.

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

5 Factory method pattern offers alternative way of creating object.
6. Factory pattern can also be used to hide information related to creation of object.

That’s all on Factory design patten in Java for now. This is one of the most used patterns in Java library and different Java frameworks. Summary is try to use Factory pattern whenever you see an opportunity to encapsulate object creation code and see chance of creating different object in near future.
Some other Java tutorial you may like

Difference between Comparator and Comparable in java

String Split Example using Regular Expression in Java

Java Generics Tutorial: Generic wildcards explained

How to deal with ClassNotFoundExcpetion in Java

Java.lang.UnSupportedClassVersionError Major Minor version problem

How to Convert Date to String in Java

How to Convert String to Date in Java

Please share with your friends if like this article

3 comments: