Monday, 20 July 2015

Factory Design Pattern in Java


           Factory pattern is one of most used design pattern in Java. This type of design pattern comes under Creational Design Pattern as this pattern provides one of the best ways to create an object.

          In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface. & this pattern provides loose coupling.
          
          In this post, we will look at complete example of the Factory Design Pattern implemented in Java. In the below example, w'll learn how to use the Factory pattern in different message types(There are three message types in the example, SMS, Email and Notification). This is one simple example.
    
          First we can create one abstract class or an interface. MessageBuilder is an abstract class having one abstract method build.
     
    public abstract class MessageBuilder {
             public abstract void build () ;
    }


          In the above  class build is not fully implemented so next we can create particular message type builder so that can extends the Messagebuilder and you can implement the build method according to that message type. In the below codes, there are three mesage type builder ,SMSMessageBuilder, EMAILMessageBuilder and NotificationMessageBuilder. and each can extends MessageBuilder abstract class and to implements the build methods. Each MessageBuilder of build method is implemented differently according to their requirement.
 
   
    class SMSMessageBuilder extends MessageBuilder {   
            public void build () {   
                      System.out.println("This is SMS message Type");   
                      // do processing SMS message type
            }
    }

    class EMAILMessageBuilder extends MessageBuilder {   
             public void build() {   
                       System.out.println("This is Email Message Type");    
                       //do proceessing EMAIL things.
             }
    }

   class NotificationMessageBuilder extends MessageBuilder {   
            public void build () {   
                   System.out.println("This is Notification Message Type");    
                   // do processing Notification things.
           }
   }

      Next step is to define the Factory class, in this case which is a MessageBuilderFactory. As you can see in the below code, the static getBuilder method will return particular "MessageBuilder" object based on the parameter messageType.

   
 class MessageBuilderFactory {
       
      public static MessageBuilder getBuilder(String messageType) {   
              if (messageType.equals("SMS")) {           
                       return new SMSMessageBuilder();           
              } else if (messageType.equals("EMAIL")) {           
                       return new EMAILMessageBuilder();       
              } else if (messageType.equals("NOTIFICATION")) {           
                       return new NotificationMessageBuilder();       
              } else {
                       return new SMSMessageBuilder();         //default MessageBuilder.

              }
       }
 }

    Next step is to create the main class to test the above the Factory class to passing the messageType.
you can pass any type of messageType and check it. 
    
 class MessageManager {
       public static void main(String[] args) {       
              String messageType = "SMS";       
              MessageBuilder builder = MessageBuilderFactory.getBuilder(messageType);
              builder.build();   
      }
 }

 Output:-
                      This is SMS message Type.

           If you want to add new message type in the above existing code then you have to create one  Implemented MessageBuilder class that can extends abstract MessageBuilder class. In the MessageBuilderFactory you can add one else if condition and to pass messageType as parameter.

 Factory Pattern Examples in JDK:

1) valueOf() method which returns the object created by factory equivalent to parameter passed.
2) java.util.Calendar, ResourceBundle and NumberFormat of getInstance() method uses Factory Pattern.
  
 Advantages of Factory Design Pattern:

1) code is flexible, loosely coupled and reusable by moving the object creation from the client  code
    to the Factory class and it's subclasses. It is easier to maintain such code since the object creation        is centralized.
2) The client code deals with only the product interface  or abstract and hence any concrete        
     products can be added without modifying client code logic.
3) It encourages a consistency in the code as object is created through a Factory which forces a 
    definite set of rules which everybody must follow(other developer can easily understand the code). 
    This avoids using different constructor at different client.



Related Post:-- 
1) Singleton Design Pattern in Java With Example
2) What is IOC Container in Spring? Difference between BeanFactory and ApplicationContext
3) String Interview Questions and Answers
4) What are different Spring Bean Scopes?
5) Spring MVC with Hibernate CRUD Example
6) What are different states of an entity bean in Hibernate?