What are Factory Methods and Why Use Them?

The concept of factory methods is very useful and very simple at the same time. It is simple enough to explain and I would not need to write a long post for that!

Basically a factory method is a method which returns an object (just like a factory manufactures goods -a factory method manufactures an object -and that’s why the name). To understand it with an example, lets assume you have an interface, very creatively called MyInterface, which you want to implement. So, you implement it in a class called, say, FirstImplementation. And then you make use of FirstImplementation in, say, 120 odd other classes in your software. All ok so far!… But the problem will arise if you need to use a different implementation of MyInterface. Your options would be:

  1. Overwrite the code in the FirstImplementation with the code of new implementation
  2. Write the new implementation in another class, say, SecondImplementation and change all of the 120 odd classes to refer to the SecondImplementation.
  3. Use a factory class

Well, the first option is feasible. But in that case you will lose the code of the FirstImplementation. This is not a very neat way to solve the problem.

Second option is simply nightmarish! Only programmers as diligent as computers will attempt it as you will have to change 120 odd classes.

Third option is beautiful, neat and smart. You just create a new intermediate class, say FactoryClass, and use this class to get the instance of the FirstImplementation in your 120 odd classes. Now, if you would need to use a different implementation of MyInterface -all you need to do is just to modify the code in the FactoryClass.

public interface MyInterface{
//define members
}

public class FirstImplementation{
//implement MyInterface
}

public class FactoryClass{

//constructor come here

//write more methods if neede
public MyInterface getInstance(){
MyInterface a=new FirstImplementation();
return a;
}

public class UserClass{
FactoryClass faObj = new FactoryClass();
MyInterface myInter=faObj.getInstance();
}

So now if you decide to implement MyInterface as SecondImplementation -all you need to do is to change the code in the FactoryClass. You don’t need to touch the UserClass(es) for this.

Did you get the idea? If you’re still in doubt about the concept of factory methods, feel free to comment and ask me. I will try to help you.

1 thought on “What are Factory Methods and Why Use Them?”

  1. Very clearly explained the problem domain. I know how factory pattern works but I did not really understand why would one want to use that, except additional complexity. I liked the way you explained why do we need this patter in real example.

Leave a Comment

Your email address will not be published. Required fields are marked *