Factory Method Design Pattern

05/11/2009

A factory method pattern is a creational pattern. It is used to instantiate an object from one among a set of classes based on a logic.

Assume that you have a set of classes which extends a common super class or interface. Now you will create a concrete class with a method which accepts one or more arguments. This method is our factory method. What it does is, based on the arguments passed factory method does logical operations and decides on which sub class to instantiate. This factory method will have the super class as its return type. So that, you can program for the interface and not for the implementation. This is all about factory method design pattern.

Sample factory method design pattern implementation in Java API

For a reference of how the factory method design pattern is implemented in Java, you can have a look at SAXParserFactory. It is a factory class which can be used to intantiate SAX based parsers to pares XML. The method newInstance is the factory method which instantiates the sax parsers based on some predefined logic.

Block diagram for The Design Pattern

factorydesignpattern

Sample Java Source Code for Factory Method Design Pattern

Based on comments received from users, I try to keep my sample java source code as simple as possible for a novice to understand.

Base class:

package com.javapapers.sample.designpattern.factorymethod;

//super class that serves as type to be instantiated for factory method pattern
public interface Pet {

 public String speak();

}

First subclass:

package com.javapapers.sample.designpattern.factorymethod;

//sub class 1 that might get instantiated by a factory method pattern
public class Dog implements Pet {

 public String speak() {
 return "Bark bark...";
 }
}

Second subclass:

package com.javapapers.sample.designpattern.factorymethod;

//sub class 2 that might get instantiated by a factory method pattern
public class Duck implements Pet {
 public String speak() {
 return "Quack quack...";
 }
}

Factory class:

package com.javapapers.sample.designpattern.factorymethod;

//Factory method pattern implementation that instantiates objects based on logic
public class PetFactory {

 public Pet getPet(String petType) {
 Pet pet = null;

 // based on logic factory instantiates an object
 if ("bark".equals(petType))
 pet = new Dog();
 else if ("quack".equals(petType))
 pet = new Duck();
 return pet;
 }
}

Using the factory method to instantiate

package com.javapapers.sample.designpattern.factorymethod;

//using the factory method pattern
public class SampleFactoryMethod {

 public static void main(String args[]){

 //creating the factory
 PetFactory petFactory = new PetFactory();

 //factory instantiates an object
 Pet pet = petFactory.getPet("bark");

 //you don't know which object factory created
 System.out.println(pet.speak());
 }

}

Output of the above sample program for Factory Method Pattern

Bark bark

Download Java Source Code For Factory Method Pattern

Nice!!. Though I am using all but when i try to related to design pattern, normally it looks me like big sky infront of me.

But you explined neatly.

Thanks for your effort and time for writing this ariticle.

Thanks
Thamayanthi

Thamayanthi on November 6th, 2009 12:30 pm

Factory is one of the widely used design patterns. Happy that you are able to relate it. Good luck Thamayanthi!

Tutorials and articles available on internet try to be comprehensive and consequently confuses the reader. I try to keep my definitions as simple as possible for users to get the fundamental understanding right. So that, over experience they can build on top of it.

Design patterns are not a complex subject. With appropriate tutorials it will be interesting to learn and use.

Joe on November 6th, 2009 1:41 pm

actualy i was using this design pattern only for creating object but not for return the object of super class based on logic.
so it is now clear to use this design pattern

thanks

Rampratap on November 7th, 2009 10:03 am

Best wishes Rampratap.

Joe on November 7th, 2009 10:33 am

[...] To keep things simple you can understand it like, you have a set of ‘related’ factory method design pattern. Then you will put all those set of simple factories inside a factory pattern. So in turn you need [...]

Abstract Factory Pattern&hellip on November 11th, 2009 9:31 pm

This is good article. explained in very clear understanding way.

Thanks for your post.

Ram on February 4th, 2010 12:34 pm

Thanks

Simple and Nice explanation. Able to understand the basic defenition of the Factory methods.

dilip on February 18th, 2010 6:24 am

Nice and simplified explaination of a good design pattern..Good effort

Prachi Gupta on March 4th, 2010 5:31 pm

Really good. I have understood it now. Thanks a lot

vruddhi on June 25th, 2010 6:26 am

The example is good. but to make it more apparent with the definition put the public Pet getPet(String petType) in an interface and let PetFactory inplement this interface. Reason any conventional definition tell you that there are four aspects to Factory Method.

1. Product — in your case it is Pet. The interface of objects created by the factory

2. Concrete Product — in your case it is Dog and Duck .The implementing class of Product. Object of this class is created by ConcreteCreator.

3. Creator — Which is the interface i am talking about. This interface defines the factory methods

4. Concrete Creator — PetFactory in your case. This class that extends Creator and that provides an implementation for the factoryMethod. This can return any object that implements Product interface.

This will give the readers exact implementation for Factory Method.

Amardeep Singh on July 15th, 2010 5:00 am

hi Joe, thanks for the great explanation…

I have a question:

If the getPet() method in PetFactory class only determines whether to create a new Dog() or new Duck() based on String petType, then can we not make this getPet() method a static method.. and therefore in our main() method we wont have to create an instance of the PetFactory type… and instead we would be able to use the following statement

Pet pet = PetFactory.getPet(“bark”);

Which is the better way… instantiate PetFactory like you did… or don’t instantiate like pointed out in this comment… ?

Thank you for your time

abhay on August 1st, 2010 6:15 pm

Hi Joe,
Very good articles
- Senthil

Senthil Kumar on November 12th, 2010 6:40 pm

very nice explanation,now I understand factory pattern.

Thanks,

Eman Ahmed Elsayed on December 26th, 2010 10:53 pm

Very nice way to explain. I am always feeling that design pattern are very difficult to understood.

Now you made it very simple and easy way to learn all design patterns.

Thank you very much.

Regards
Sreeni

Sreeni on February 4th, 2011 6:18 am

No doubt ,its very simply explained ….But what about Abhay ‘s question? I am agree with him….

prashant on February 16th, 2011 8:43 am

Thanks Joe…. u explained the concepts in a pristine manner…i became ur fan..

vamsi on April 16th, 2011 7:02 am

Thanks Joe…. u explained the concepts in a pristine manner…i became ur fan..

vamsi on April 16th, 2011 7:02 am

[...] If you want to provide a handle / method to deliver a copy of the current instance write a kind of factory method and provide it with a good documentation. When you are in a situation to use a third party [...]

Java Clone, Shallow Copy &hellip on June 10th, 2011 9:16 am

Could you please give an example about combining strategy & factory patterns ?

ozgun on December 7th, 2011 10:39 pm

hi,
Please move the search button in your page to the top. It will be more user friendly.

Regards,
Balaji A

Balaji A on December 15th, 2011 8:25 am

nice job

Vishnu on December 29th, 2011 8:39 am

The example you have given more suits to Fatory Pattern not factory method pattern.

The exact definition for factory method pattern is to “define an interface for creating an object, but let subclasses decide which class to instantiate. Lets a class defer instantiation to subclasses”.

Noor on January 16th, 2012 7:00 am

Very Easy to understand

Thanq very much

Sudheer on February 2nd, 2012 1:26 pm

Thanks Sir, it is simple and well framed explanation.

Karan Krishan on February 15th, 2012 2:34 pm

it was really a good understanding after reading the explanation

Mau on February 16th, 2012 11:46 am

good effort.

vithak on February 19th, 2012 10:45 pm

Good one.

Santosh on March 6th, 2012 3:32 pm

very nice …updated and adequate.Kindly provide a link for PDF of all your post if possible

Anju on March 7th, 2012 11:17 am

nice man, thank you for your passionate

Arunkumar on March 7th, 2012 2:38 pm

Anju, sure I am working on creating downloadable PDF files but will take some time.

Joe on March 7th, 2012 7:23 pm

Joe nice explanation, but according to the definition of Factory Method ” Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.” But here how the subclasses deciding which clas to instantiate?

Jam on March 13th, 2012 4:56 pm

Thanka Lot Joe.. you know I never seen such a simple and easy explanation to understand the factory method design pattern.. you rock it. Keep up the good work buddy…

-Lokesh

Anonymous on March 27th, 2012 1:45 pm

Nice Example for this design patterns
i like it

Anil on March 29th, 2012 6:29 pm

I’m a regular visitor to your site now…luv d way u explain things so tersely & easy 2 comprehend..gr8 work man…u rock !!!..
Pls keep posting more such JAVA stuff…:-)

Mukul Pandey on March 30th, 2012 2:48 am

Hi joe,

Thanks for explaining the concepts so clearly.

Anonymous on April 3rd, 2012 3:09 pm

good and simple presentation and useful to plenty of students for references

n.srinivasarao on April 3rd, 2012 4:32 pm

great job

balaji on April 10th, 2012 2:41 pm

Neat And clean Explanation ,thank god u provided the download file otherwise it would b mystery for me.. Finally understood..

Anonymous on April 11th, 2012 6:38 pm

Thanks for your effort and time for writing this ariticle.

Yogesh Dhawale on April 17th, 2012 4:05 pm

Nice article on Design pattern, Thanks Joe.

Siva on April 23rd, 2012 6:38 pm

Thanks a lot…..i was just getting frustrated reading a hard written book
You have a great skill of presentation and making things easy

safat on April 24th, 2012 5:31 pm

Good one! Short and crisp!!

Mugdha on May 4th, 2012 1:51 pm

super Joe, awesome no words to describe,I’m a new Java developer having just 1.5 years experience, luckily got here, i thought of leaving Java coz of poor understanding,now i realized that its damn easy if we understand things.

Sai on May 10th, 2012 12:43 pm

plz put the sequence diagram for this pattern

Anonymous on May 10th, 2012 11:48 pm

I red almost all the design patterns.It was a wonderful presentation.I am now capable of designing my classes with patterns.Thanks a lot!

Misge on May 23rd, 2012 7:28 pm

Good Website Joe.
I have also read your articles on Core java, JSP and Servlets. The way you explain concepts is really good and easy to understand.
Is there any difference between Factory Design Pattern and Factory Method Design Pattern

Rashmi on May 24th, 2012 5:05 pm

Good one! Short and crisp!!

Chetanya on May 24th, 2012 5:19 pm


Email:

about
I am Joe, author of this blog. I run this with loads of passion. If you are into java, you may find lot of interesting things around ...more about me. Google+
java badge
Home