Factory Pattern in java - Java @ Desk

Tuesday, June 4, 2013

Factory Pattern in java

In factory design pattern, there is a factory java class that hides the object creation from outside world. In this pattern, the object creation depends on the data passed as an argument to the factory class and the factory class decides based on the argument passed, object of which class needs to be instantiated and returned.

This pattern provides abstraction or interface implementation and the factory class generally creates an object of subclass and returns the same.

Consider a simple scenario of IT industry where employees from IT team gets a variable payout every year where other departments like HR or Admin does not get.


public abstract class Employee { public abstract boolean getVariablePay(); public abstract String getDepartment(); }

extends employee

public class ITEmployee extends Employee {

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

    @Override
    public String getDepartment() {
        return "IT";
    }

}

extends Employee

public class AdminEmployee extends Employee {

    @Override
    public boolean getVariablePay() {
        return false;
    }

    @Override
    public String getDepartment() {
        return "Admin";
    }

}

– This class decides which object will be instantiated and returned based on employee type

public class FactoryEmployee {

    public Employee getEmployee(String employeeType) {
        if (employeeType.equals("Admin")) {
            return new AdminEmployee();
        } else if (employeeType.equals("IT")) {
            return new ITEmployee();
        }
        return null;

    }
}

- This class will show to demo of how the factory pattern works

public class DemoFactory {

    public static void main(String args[]) {
        FactoryEmployee factoryEmployee = new FactoryEmployee();
        Employee employeeOne = factoryEmployee.getEmployee("Admin");
        System.out.println("Variable pay indicator for employee 1 : " + employeeOne.getVariablePay());

        Employee employeeTwo = factoryEmployee.getEmployee("IT");
        System.out.println("Variable pay indicator for employee 2 : " + employeeTwo.getVariablePay());
    }
}


The console output is shown here.

Console Output

Variable pay indicator for employee 1 : false
Variable pay indicator for employee 2 : true








No comments:

Post a Comment