Factory Method Pattern in Java

By | 2015-06-01T02:14:21+05:30 June 1st, 2015|DessignPatterns|

Factory Method Pattern is one of the most commonly used pattern in Java and C# languages. The pattern is comes under creational design pattern from the GoF (Gang Of Four) Book. In Factory Pattern Objects will be created without exposing the creation logic and refers the new created objects to a common interface.

What is Factory Method Pattern ?

The Factory Design pattern defines an interface to create an object and let the sub classes decide which instance to create.  The subclasses are responsible for creating the class instances. The Pattern is also called as the Virtual Constructor.

Advantages:

  1. For choosing the type of objects with the sub-classes, the Factory Method Pattern is useful.
  2. Factory Pattern also allows the loose-coupling through eliminating all the bind application classes for the code. The code also interacts with any of abstract class or resultant interface.
  3. It creates the Objects with out exposing the instantiation logic.

Example For Factory Method Pattern

Here we are going to discuss about the Car example, with respect to the Factory Method Pattern. When we think about a Car, we don’t get complete picture of the Car. Because the Car is an abstract representation i.e every Car can have 4 wheels, 4 doors, 1 steering and etc. Hence for complete representation, we should talk about whether it is Audi Car, Benz Car or some other else.

In the below example we are going to represent the Car with  Factory Method Pattern.

Factory Method Pattern

Here the Car is an Abstract Class and Audi, Benz are the concrete implementations of the Car. By using the Car Factory, client (Factory Pattern) can get the Objects according to the input with out knowing the object creation logic.

Step 1:

Creating  an abstract class for Car.

abstract class Car {

    public final int WHEELS = 4;
    protected String name;

    public abstract float horsePower();

    public abstract boolean isSedanModel();

    public abstract String basePrice();

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Step 2

Creating one of the concrete implementation (Audi) for Car class.

class Audi extends Car {

    String name = "Audi S7";

    @Override
    public float horsePower() {
        return (float) 450.00;
    }

    @Override
    public boolean isSedanModel() {
        return true;
    }

    public String getName() {
        super.setName(name);
        return super.getName();
    }

    @Override
    public String basePrice() {
        return "$82,900";
    }
}

Step 3

Creating another concrete implementation (Benz) of Car class.

class Benz extends Car {

    String name = "benz c300";

    @Override
    public float horsePower() {
        return (float) 241.00;
    }

    @Override
    public boolean isSedanModel() {
        return true;
    }

    public String getName() {
        super.setName(name);
        return super.getName();
    }

    @Override
    public String basePrice() {
        return "$41,325";
    }
}

Step 4

Creating the CarFactory class, from which Objects are created based on the type.

class CarFactory {

    public static Car getCarFactory(String car) throws Exception {
        if (car.equals("Audi S7")) {
            return new Audi();
        } else if (car.equals("benz c300")) {
            return new Benz();
        } else {
            throw new Exception("In valid Car Name");
        }
    }
}

Step 5

Creating the client class to access the CarFactory.


public class FactoryPattern {

    public static void main(String[] args) throws Exception{
        System.out.println("Please Enter the Car name for Details");
        Scanner s = new Scanner(System.in);
        String carName = s.nextLine();
        System.out.println("======================================");
        Car carFactory = CarFactory.getCarFactory(carName);

        System.out.println("Name : " + carFactory.getName());
        System.out.println("BasePrice : " + carFactory.basePrice());
        System.out.println("HorsePower : " + carFactory.horsePower());
        System.out.println("isSedanModel : " + carFactory.isSedanModel());
        System.out.println("wheels : " + carFactory.WHEELS);
    }
}

Output:
Please Enter the Car name for Details
Audi S7
======================================
Name : Audi S7
BasePrice : $82,900
HorsePower : 450.0
isSedanModel : true
wheels : 4

In this example, FactoryPattern is a client class, from which we are going to get the Car Objects. CarFactory class is responsible for creating the Objects with respect to the client input. Here the Object creation logic is implemented under CarFactory, and Client (FactoryPattern class) doesn’t know the creation logic.

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment