Factory Method Pattern

Factory method pattern enables us to create object without exposing the creation logic to the client and refer to newly created object using a common interface. It is one of the most widely used creational pattern.

This pattern is also known as Virtual Constructor.

The intent of this pattern, according to Design Patterns by Gamma et al, is to

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Factory Method is for creating objects. A superclass specifies all standard and generic behavior, and then delegates the creation details to subclasses that are supplied by the client.

Factory Method makes a design more customizable and only a little more complicated. Other design patterns require new classes, whereas Factory Method only requires a new operation.

 

Structure

The structure of factory method pattern is as shown in figure below:

factory-method-pattern-structure

Figure: Structure of Factory Method Pattern

Now-a-days, a static method of a class is popularly used as a factory method that returns an object of required class' type. Unlike a constructor, the actual object it returns might be an instance of a subclass and also an existing object might be reused, instead of a new object created.

One of advantage using factory instead of a constructor is that factory methods can have different and more descriptive names.

 

Example

Let us consider an application which draws different geometic shapes on the basis of clien't demand. The class diagram of the applicaton is as shown below:

factory-method-pattern-example

Figure: Factory Method Pattern Example

ShapeFactory class has a static method getShape() which return the GeometricShape object on the basis of string name input.

 

Java Implementation

We've presented Java implementation of the application discussed above.

Let's first create an interface for product to be manufactured by factory.

/**
 * Product interface
 */
public interface GeometricShape {
    void draw();
}

The following are the implementation of the interface above.

/**
 * Concrete Product
 */
public class Line implements GeometricShape {
    @Override
    public void draw() {
        System.out.println("Line Drawn.");
    }
}
/**
 * Concrete Product
 */
public class Rectangle implements GeometricShape {
    @Override
    public void draw() {
        System.out.println("Rectangle is drawn.");
    }
}
/**
 * Concrete product
 */
public class Circle implements GeometricShape{
    @Override
    public void draw() {
        System.out.println("Circle is drawn.");
    }
}

Now, let's create factory that provides product ( in this case GeometricShape).

/**
 * Concrete Product
 */
public abstract class ShapeFactory {
    //gives geometric shape on the basis of input string name
    public static GeometricShape getShape(String name){
        if(name.equals("line")){
            return new Line();
        }else if (name.equals("circle")){
            return new Circle();
        }else if (name.equals("rectangle")){
            return new Rectangle();
        }
        return null;
    }
}

The client for the application provides the the name of the shape required as follow.

/**
 * Client
 */
public class Application {
    public static void main(String[] args) {
        //requests for circle shape
        GeometricShape circle = ShapeFactory.getShape("circle");
        if (circle != null){
            circle.draw();
        }else {
            System.out.println("This shape can not be drawn.");
        }
        //requests non existent shape 
        GeometricShape triangle = ShapeFactory.getShape("triangle");
        if(triangle != null){
            triangle.draw();
        }else {
            System.out.println("This shape can't be drawn");
        }
    }
}

The output of the program is:

Circle is drawn.
This shape can't be drawn

Since, there exists circle shape, a valid Circle object is returned. But, there is no class with triangle, so the shape can't be drawn.

Note: Difference between Factory and Template Pattern is that Factory Method is for creating objects as Template Method is to implementing an algorithm.

Chain of Responsibility Pattern
Abstract Factory Pattern