Java Design Pattern: Factory

1. The story for Factory pattern

Factory design pattern is used for creating an object based on different parameters. The example below is about creating human in a factory. If we ask the factory for a boy, the factory will produce a boy; if we ask for a girl, the factory will produce a girl. Based on different parameters, the factory produce different stuff.

2. Factory pattern class diagram

factory-design-pattern

3. Factory pattern Java code

interface Human {
	public void Talk();
	public void Walk();
}
 
 
class Boy implements Human{
	@Override
	public void Talk() {
		System.out.println("Boy is talking...");		
	}
 
	@Override
	public void Walk() {
		System.out.println("Boy is walking...");
	}
}
 
class Girl implements Human{
 
	@Override
	public void Talk() {
		System.out.println("Girl is talking...");	
	}
 
	@Override
	public void Walk() {
		System.out.println("Girl is walking...");
	}
}
 
public class HumanFactory {
	public static Human createHuman(String m){
		Human p = null;
		if(m.equals("boy")){
			p = new Boy();
		}else if(m.equals("girl")){
			p = new Girl();
		}
 
		return p;
	}
}

4. Factory design pattern used in Java standard library

Based on different parameter, getInstance() returns a different instance of Calendar.

java.util.Calendar - getInstance()
java.util.Calendar - getInstance(TimeZone zone)
java.util.Calendar - getInstance(Locale aLocale)
java.util.Calendar - getInstance(TimeZone zone, Locale aLocale)
java.text.NumberFormat - getInstance()
java.text.NumberFormat - getInstance(Locale inLocale)

You can view the source code of Calendar and NumberFormat in javased.com.

Category >> Design Patterns Stories  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Anil Nivargi

    Thanks for good explanation…..please go through this blog http://adnjavainterview.blogspot.in/2015/07/factory-design-pattern-in-java.html also explained good..

  • ryanlr

    I don’t understand your question, can you be more specific?

  • ryanlr

    corrected, thanks!

  • ryanlr

    corrected. Thanks!

  • ryanlr

    Glad to know the post is useful to you. Thanks for subscribing!

  • Curtis Newton

    what about a more generic example, when you dont know the precise class
    for instance if you got a list of classes that inherits a mother class ?

  • Aayush Bahuguna

    Nice example.

    In HumanFactory for string comparison should m.equals(“boy”) / m.equals(“girl”) be used?

  • malphix

    method’s name lower….

  • jeff

    equals

  • ryan

    lol. Java people.

  • guest

    Nice example, but when you compare String objects you should always use the equals method otherwise your factory object will always return null…

  • Ezequiel Gustavo Martinez

    Good tutorial for this design pattern! I couldn’t find out some examples like this (easy and not confused haha) I’ll subscribe me to your newsletter. Good bye and greetings from Argentina !

  • Guest

    Buen tutorial para este modelo de diseño! No pude encontrar algunos ejemplos como este (fácil y no confundir jaja) me voy a suscribirse a su boletín de noticias. Adiós y saludos desde Argentina!

  • Vetri

    typo mistake

    class registration with or without reflection

  • Vetri

    it s very good but this procedural approach is not a good idea in OOPS. if we have 10 or 20 classes implemented the Human interface . crateHuman(String) by String will be unreadable. so in a standard way you can use class registration with or without to avoid if else check in factory. since java reflection affects the performance by 10% . you can go with class registration without reflection .
    for example.
    Load all the classes before registering into factory using Class.forName() in order for this to work .

    Class.forName(“Boy”);
    Class.forName(“Girl”);

    interface Human {
    public void Talk();
    public void Walk();
    public Human createHuman();
    }

    class Boy implements Human {

    static {
    HumanFactory.getInstance().registerHuman(“boy”,new Boy());
    }

    @Override
    public Human createHuman() {
    return new Boy();
    }

    @Override
    public void Talk() {
    System.out.println(“Boy is talking…”);
    }

    @Override
    public void Walk() {
    System.out.println(“Boy is walking…”);
    }
    }

    class Girl implements Human{

    static {
    HumanFactory.getInstance().registerHuman(“girl”,new Girl());
    }

    @Override
    public Human createHuman() {
    return new Girl();
    }

    @Override
    public void Talk() {
    System.out.println(“Girl is talking…”);
    }

    @Override
    public void Walk() {
    System.out.println(“Girl is walking…”);
    }
    }

    public class HumanFactory {
    private static HumanFactory humanfactory;
    private Hashtable humanGroup = new Hashtable();

    public static HumanFactory getInstance() {
    if (humanfactory == null) {
    synchronized(HumanFactory.class) {
    if (humanfactory == null) {
    humanfactory = new HumanFactory();
    }
    }
    }
    return humanfactory;
    }

    public void registerHuman(String name,Human human) {
    humanGroup.put(name,Human);

    }

    public Human createHuman(String m){

    Human human = (Human)humanGroup.get(m);
    return human.createHuman();

    /*Human p = null;
    if(m == “boy”){
    p = new Boy();
    }else if(m == “girl”){
    p = new Girl();
    }

    return p;*/
    }
    }

  • eee

    very good

  • java_learner

    good

  • abc

    The method is repeat