A Java Factory Pattern example

Java Design Patterns FAQ: Can you provide an example of the Factory Pattern in Java?

Sure. In this article we'll look at a small-but-complete example of the Factory Pattern ("Factory Design Pattern") implemented in Java.

In this example, we'll create a simple "dog factory" that can return a variety of Dog types, where the "Dog" that is returned matches the criteria we specify. For instance, we might tell our factory that we want a small dog, or a large dog, and the dog factory will give us a dog of the type we asked for.

The idea for this article isn't to get too deep into the theory of the factory pattern, but instead, to demonstrate a Java factory pattern example.

The Dog interface

First, we'll create a Dog interface. Any dog that our factory returns must implement this Java interface, so for the purposes of our example, we'll keep this interface very simple. We'll just specify that any class that calls itself a Dog must implement a speak method that looks like this:

interface Dog
{
  public void speak ();
}

The concrete Dog classes

Next, we'll define a few concrete classes that implement our Dog interface. Keeping with our simple interface, each class implements the speak method, but implements it in a slightly different way that befits each dog type:

class Poodle implements Dog
{
  public void speak()
  {
    System.out.println("The poodle says \"arf\"");
  }
}

class Rottweiler implements Dog
{
  public void speak()
  {
    System.out.println("The Rottweiler says (in a very deep voice) \"WOOF!\"");
  }
}

class SiberianHusky implements Dog
{
  public void speak()
  {
    System.out.println("The husky says \"Dude, what's up?\"");
  }
}

As you can see from the code, each of these concrete classes (Poodle, Rottweiler, and SiberianHusky) implements our Dog interface. This is a key point, and an important part of the Factory Pattern:

You define a base class type (or in this case an interface), and then have any number of subclasses which implement the contract defined by the base class.

And as you're about to see, the signature of the factory method shows that it will be returning a class which implements our base class, in this case, our Dog interface.

The Java Factory class

Next we'll define our Java Factory class, which in this case is a DogFactory class. As you can see from the code below, the DogFactory class has a static getDog method that returns a "Dog" depending on the criteria that has been supplied.

class DogFactory
{
  public static Dog getDog(String criteria)
  {
    if ( criteria.equals("small") )
      return new Poodle();
    else if ( criteria.equals("big") )
      return new Rottweiler();
    else if ( criteria.equals("working") )
      return new SiberianHusky();

    return null;
  }
}

As I mentioned, the signature of our Java factory method states that we will be returning a class of type Dog:

public static Dog getDog(String criteria)

The factory doesn't say it's returning a Poodle, Rottweiler, or SiberianHusky-- it just says it's returning something that implements the Doginterface.

Also, it's very important to note that in this simple example I'm only accepting strings like "small", "big", and "working" as my "criteria". In a more complicated (real world) example, you'll want to tighten down this code much more.

The Java Factory pattern example driver program

Now that we've created our dog factory, our Dog interface, and all of our dog types, we'll create a "driver" program named JavaFactoryPatternExample to test our Dog factory. This driver class demonstrates how to get different types of dogs from the factory:

/**
 * A "driver" program to demonstrate our "dog factory".
 * @author alvin alexander, devdaily.com
 */
public class JavaFactoryPatternExample
{
  public static void main(String[] args)
  {
    // create a small dog
    Dog dog = DogFactory.getDog("small");
    dog.speak();

    // create a big dog
    dog = DogFactory.getDog("big");
    dog.speak();

    // create a working dog
    dog = DogFactory.getDog("working");
    dog.speak();
  }
}

As you can see from our driver class, we create an instance of each type of dog (small, big, and working).

Discussion

My intent here isn't to get too deep into the theory behind the Factory Pattern, but instead to demonstrate the pattern in Java source code. That being said, there are a couple of quick points I'd like to make about the Factory Pattern:

  • A simple factory like this returns an instance of any one of several possible classes that have a common parent class.
  • The common parent class can be an abstract class, or an interface, as I've shown here.
  • The calling program typically has a way of telling the factory what it wants, and the factory makes the decision which subclass should be returned to the calling program. It then creates an instance of that subclass, and then returns it to the calling program.

There are several design patterns that are closely related to the Factory Pattern, including the Factory Method Pattern, and the Abstract Factory Pattern, but I believe this is a correct example of a simple Factory Pattern.

Download our example source code

I'm providing all of this code in one file, so you can download our Java Factory Pattern example and experiment with it as desired.

thx

this pattern example help me a lots. Thankyou verymuch.

Very Helpful

Thanks a ton for this example. Really well thought out, and I felt it cut right to the heart of factory patterns and provided a nice simple example. Thanks again!

Good

Its very useful for me.i dont know concept of factory pattern but
once i read this and very clear this factory concept.

Thank you so much..

Simple and Precise

Thank you for the neat example. doesnt confuse like many other examples available on net.

Nicely Explained.Thanks!

Alvin,

Factory pattern concept is very nicely explained by you.

Thanks a lot.

Excellent! You are a talented

Excellent! You are a talented mentor

very good example

very good example

This is the perfect example.

This is the perfect example. i read from so many links but it was not able to understand but this example is so clear.
Thanks

Great article

Really thanks for the article .. It's really simple and easy to understand.

cK

Good example

Nice example, but just to mention that the Factory could be abstracted as well, so we could modify and implement different factories at will. Good example otherwise

Simple but good example

Great many thanks to the author: Alvin.

Simple and clear example. Quite easy to understand and easy to recollect in future.

Thanks... It was really

Thanks...

It was really helpful for me.
Thanks again....

very very good

the best way to explain is to smplify things. It's very gud example.

Thanks a lot

Well Explained... crisp ,

Well Explained... crisp , straight to the point !!

GENIAL EXPLANATION

Amazing explanation man. WOOF.

Simple and good example to

Simple and good example to understand the concept of factory pattern

Thanks a lot!

thanks, it's very easy for understanding.

Thanks!

Great article, helped me a lot understanding this concept. Thanks!!!

Very simple to understand

It was straight to the point and easy to digest. I reviewed several others online but no one was as simple as your. Thanks

Very Clean Thanks

This as an excellent simple example that cleared up the concept for me.

Very easy to understand ..

Very easy to understand .. well explained

Nice and clean example.

Nice and clean example. Thanks, I needed the recap. ;)

Post new comment

The content of this field is kept private and will not be shown publicly.