
What is a Factory?
Factory is a place where objects are produced and dispatched. This is the traditional definition.
Coming to Java, Factory pattern says that define an interface and let the sub classes decide which object we should instantiate. So there is something like a factory method which takes a parameter and returns the required object. So loose coupling is achieved by doing this and tight coupling is eliminated.
But the main point here is that object which is returned should be a sub class of the Interface to which it would be tied. Something like below (Employee is an interface).
Employee emp = factory.get(“Manager”);
The above factory object would fetch us probably the manager object and tie it to the emp property. We don’t know the internal creation process of that object as it is hidden.Factory would be handling it internally. Note that Manager Class should implement the Employee Interface. Since this pattern deals with creation of objects, it is an creational design pattern.
Let’s look an at an example below in which we create an interface and create sub classes which implement the interface.
public interface Employee {
void performTask();
}
public class Engineer implements Employee{
@Override
public void performTask(){
System.out.println("Performing Engineering Task");
}
}
public class Manager implements Employee{
@Override
public void performTask(){
System.out.println("Performing Managerial Task");
}
}
So here we have an Employee Interface which is implemented by 2 sub classes which are Engineer and Manger. Now let’s design a factory class which would instantiate the objects of the 2 child classes and bind it to the Employee Interface.
public class EmployeeFactory {
public Employee createEmployee(String empType)
{
if (empType == null || empType.isEmpty())
return null;
if ("Mgr".equals(empType)) {
return new Manager();
}
else if ("Eng".equals(empType)) {
return new Employee();
}
return null;
}
}
So above we have created a factory which would create and return the object according to the parameter which is passed. Now let’s see the call.
Employee emp = EmployeeFactory.createEmployee("Mgr");
The above call would return the manager object. This is how a factory functions and the factory design pattern works.