Saturday, January 9, 2016

Factory Design Pattern

Factory Design pattern

 ·        Factory method is a static method of a class that returns an object of that class' type.
·         A business class shouldn’t have to know how to build a complex object it needs to use, the business class needs to focus only on business concerns.
·        Factory, as name suggest, is a place to create some different products which are somehow similar in features yet divided in categories.
·        Factory pattern is used to create instances of different classes of same type.
·        This pattern introduces loose coupling between classes which is the most important principle one should consider. 


package com.java.designpatterns;

import java.util.Scanner;

interface Shape {
      void draw();
}

class Circle implements Shape {
      @Override
      public void draw() {
            System.out.println("Circle is drawn");
      }
}

class Square implements Shape {
      @Override
      public void draw() {
            System.out.println("Square is drawn");
      }
}

/*
 * FactoryClassShape is acting as Factory class which is providing the asked
 * Object.
 */
class FactoryClassShape {
      public static Shape getShape(String shape) {
            if (shape.equals("Circle"))
                  return new Circle();
            else if (shape.equals("Square"))
                  return new Square();
            return null;
      }
}

/*
 * Creating the object without exposing the creation logic to the client and
 * refer to newly created object using a common interface
 */

public class FactoryDP {
      public static void main(String[] args) {
            System.out.println("Which shape you want to draw ?");
            Scanner scan = new Scanner(System.in);
            String s = scan.next();
            scan.close();
            Shape shape = FactoryClassShape.getShape(s);
            if (shape instanceof Shape)
                  shape.draw();
            else
                  System.out.println("Shape doesn't exist");
      }
}

As you can see, Factory is able to return any type of shape instance it is requested for. It will help us in making any kind of changes in shape making process without even touching the composing classes i.e. classes using FactoryShapeClass.
We can see many examples of factory pattern in JDK itself e.g.
·         java.net.URL#openConnection()
·         java.lang.Class#newInstance()
·         java.lang.Class#forName()

Example 1:

   public static Connection getConnection(String url)
        throws SQLException {
      java.util.Properties info = new java.util.Properties();
      return (getConnection(url, info,Reflection.getCallerClass()));   
   }

Above method is factory method as it is providing the asked Connection based on the url.

Example 2 :

   import org.slf4j.Logger;
   import org.slf4j.LoggerFactory;

   public class Example{

   public void example() {
   //we're using the static factory method to get our logger
   Logger logger = LoggerFactory.getLogger(Example.class);

   logger.info("This is an example.");
    }
   }

Usage in JDK

a) java.util.Calendar, ResourceBundle and NumberFormat getInstance() 
b) valueOf() method in wrapper classes like Boolean, Integer etc.
c) Spring and hibernate frameworks.

No comments:

Post a Comment