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

Ads by Google

119 comments on “Factory Method Design Pattern

  1. 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

  2. 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.

  3. 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

  4. Pingback: Abstract Factory Pattern

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

    Thanks for your post.

    • It is really useful and explains the concept clearly

  6. Thanks

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

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

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

  9. 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.

    • I agree with your valid points.
      Joe,
      Simplicity is good.However enough information about each design patters is more important.

  10. 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

    • Great thoughts!
      Factory pattern is used for addressing problem on object creation.

      As you rightly mentioned, method could be static (Static Factory method). So that client side no need to create object of Factory class.

      Keep it up!

      Joe,
      Please add section for Pre Request ( situations/conditions) and solution to the problems for each design pattern.

      Your effort is appreciated.

  11. Hi Joe,
    Very good articles
    - Senthil

  12. very nice explanation,now I understand factory pattern.

    Thanks,

  13. 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

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

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

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

  17. Pingback: Java Clone, Shallow Copy and Deep Copy

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

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

    Regards,
    Balaji A

  20. 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”.

    • You are right when suppose you have classes in family hierarchy that time is your idea will rightly fit.

      Here, the object creation problem is in single interface and multiple implementations.

      We may not required to implement completely which design pattern says…

      See the problem
      For Simple Problem , solution should be so simple.

      For complex problem, solution should be so so simple :)

      I agree Joe need to explain a lot about various problems on object creation with proposed solution.
      Hope Joe may like to Super Star!

  21. Very Easy to understand

    Thanq very much

  22. Thanks Sir, it is simple and well framed explanation.

  23. it was really a good understanding after reading the explanation

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

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

  25. nice man, thank you for your passionate

  26. 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?

  27. 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

  28. Nice Example for this design patterns
    i like it

  29. 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…:-)

  30. Hi joe,

    Thanks for explaining the concepts so clearly.

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

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

  33. Nice article on Design pattern, Thanks Joe.

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

  35. 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.

  36. plz put the sequence diagram for this pattern

  37. 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!

  38. 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

  39. Hi,
    Thanks for such a nice article …
    Just have a doubt ….

    what if the Factory method is static ?
    Will it violate the definition of this design pattern ?

    • No worries!
      It may not violate the definition of design pattern sir!
      It will become static factory design pattern and that is really good solution when object creation for single interface with multiple implementations.

      Some extend we could twist the design pattern for exactly fitting your current requirement and problems may come in future.

      100 % pure gold may not help us boss!

      Choosing right design pattern is more important rather than implementation (it can change as needed)

  40. Thanks for giving such clear explanation

  41. Why don’t you increase the width of your code window ? Its like viewing in a mobile. All lines are spliced and comments haywire. Just increasing the width of the central frame will help a lot.

  42. Very Nice and easy language.You finally achieved to make me understand the patterns.
    Thanks :)

  43. Really a very good and a simple explanation. Thanks a lot. It helps me to understand it better and clear.

  44. Really Good soial work….

    Hats offffffffffff

    Keep going……

  45. Can you tell how its usefull, i can intiate the directly the classes, as i am passing a parameter of a class which i need to instiate

  46. Thanks for your effort.
    I am developing code in java since 3 years but had no idea about design patterns. Now i know the importance of these. You have explained these in a very neat manner. Thanks a lot! Keep up the good work.
    One suggestion you can make singleton design pattern in more detail i.e explaining about double checked locking , volatile objects etc. This can be helpful in terms of completeness.

    • @kejul
      Thanks. Sure I will add those info in singleton pattern.

  47. All your articles in your blog are very much helpful to understand the basics.

  48. simple words, simple examples, which make complex concept clear. reading your acticle, is kind of a happy journey.
    Thanks very much for sharing!!!

  49. Really a useful article. Great work.

    Keep on sharing such a useful articles.

    Janakiraman

  50. Hi Joe,

    thanks to your Nice works? In some explanation and example i found the abstract class instead interface, so is there any specific reason/cause to use interface/abstract class one another ?

  51. Good Explaination. Is there any difference between Factory Pattern and Factory method pattern?

    • Good Question.
      You may required to move to next level for understanding about Object Creation patterns what it gives solution to the object creation problems?

      Just ask you
      what is the problem on object creation?
      Since jave provides three ways to create objects 1) new,2)Class.forname(),3) Clone !!!
      then why we need to have these many patterns ? is my question valid? if yes, go ahead!
      Best wishes :)

      • We create object Using 3 ways…
        new (Compile Time)
        Class.forName (Dynamic)
        Clone (Backup Object)

        The purpose of Object creation is different here.

        Design Pattern described here Factory Pattern, actually uses “New”

        So Its Just a way to encapsulate details of creation of objects depending on Logic.

  52. Hi Joe ,this is very good article i have ever read on design patterns

  53. Hey Joe.. I have been passionate about Design Patterns , but always get confused at some points..! Yours is a great attempt to clarify all confusions..!

    Is it right that the methods of the abstract factory patterns that create the concrete product objects, are factory methods? It seems like..

  54. Waiting for a simple but an explainatory example for Singleton Design pattern also.

  55. Thanks a lot Joe.
    Awesome artical , great & simple description of Factory pattern……

  56. thanks a lot joe for putting such a nice explanation .
    I have a question for you ??
    Till now i knew that factory method is used to create instance of those classes which have a private constructor from other classes.
    Would you like to explain the concept from this angle .

    • Your assumption may right at your angle
      When you put constructor as private.then that class must be provide static factory method for getting object from other classes.

      However Factory pattern is not only for this one exactly.

      keep your thought process until for next week !!!

  57. Hi Joe,

    Could you please post documents on Behavioral Patterns as well.

    • Sure Suresh. I am planning on behavioral patterns. You will get that soon.

  58. Thank you for such a neat example

  59. Abhay had asked a question that, we use a static method instead of using member funtion in PetFactory class. So that it is not required to be instantiate the PetFactoy.
    We all know that, static members are not related to instance scope where as its scope to class level. Static members should be loaded whenever the class loads. Joe, can you please exaplin why it is not recommonded to use a static in this scenario.

    Thank you

    • I agree Abhay point. its really sounds good.
      Please see my reply to Abhay.
      For your doubts, I could say
      Static method is going to be used.

      What is the need of variable (directly return statement is enough)

      when we used to have variable that may required to hold for future purpose.

      Factory is not going to do any logic just simply object creation and returned to client.

      hope you got my explanation.

      I really appreciate you since you raised questions from posted comments. that is really will help us to have good brain storming within us. Lets try to share our ideas.

      That is the reason I have replied around 5 to 6 members doubt today

      Always my thanks to Joe :)

  60. Hi Joe,

    Given example is not Factory Method Pattern. It is plain Simple Factory which just encapsulates object creation.

  61. Hi Joe

    The way you explained factory pattern is simple and understandable.You nicely related it with real life example.

    Other tutorials on net had really confused me and I could have never used it as it was not clear to me.

  62. really nice sample for factory design pattern

  63. No Site gave me such a great understanding..Great job.

  64. That’s very good article.
    I have a question:
    If I will add another class extend pet, do I will have to modify the factory method?

  65. Too simple to describe with examples. Awesome Joe anna:)

  66. This article explains design pattern with simple examples. Great help Joe!

  67. That was simple & precise explanation.
    Very helpful.

  68. I have set javapaers.com as my home page. Its really really good.

  69. There’s an issue with definitions here. The example presented is not a “factory method” as defined in the gang of four. A factory method delegates the creation of an object to subclasses of a parent factory or interface. Each subclass creates just one type of object.

    The example here is at times called a factory pattern or a simple factory. This type of pattern has one class containing branch instructions that are used to create one of a number of objects, as PetFactory does here.

  70. Super sir….thank you very much and do keep blogging..

  71. Great Post Sir now i understand what the factory pattern is…can u please update your blog with other factory pattern with sample code so that it will help us.

  72. Hi Joe, Can u pls mention Why we are going to Factory Method Design pattern?

  73. Very Nice article. Recently I attended an interview and was not able to draw the diagram,but next time I will not miss explaining this.Thanks a ton.

  74. Thnx a lot…. Joe.

    can u please tell me that what is the exact differences between Factory and Proxy?

  75. Thank you very much.. really good explanation…

  76. good way to explain complex things…. keep it up

  77. Great example. Thanks, Joe. I appreciate the way you have reduced this to the minimum.

    –Steve

  78. realy u r explained in simpleway.this concept was helpfull to me

  79. You r the best Sir!!! Explanation at its best!!!

  80. Here we are creating 2 objects,
    1) Instantiating Factory class.
    2) Then asking for Pet object.

    If we make factory method as a static method then is it a problem??

  81. Nice explanation. Simple and easy to understand. Thank you.

  82. It seems simple factory pattern not the factory method pattern

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

ABOUT
I am Joe, author of this blog. I run javapapers with loads of passion. If you are into java, you may find lot of interesting things around.
Ads by Google
STAY in TOUCH:

Email:

Core Java | Servlet | JSP | Design Patterns | Android | Spring | Web Service | © 2008-2012 javapapers.