A Java Factory Pattern example

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

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

In this example, I'll create a simple "dog factory" that can return a variety of Dog types, where the “Dog” that is returned matches the criteria I specify. For instance, I might tell our factory that I want a small dog, or a large dog, and the dog factory will give me a dog of the type I 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.

Back to top

A Dog interface

First, I'll create a Dog interface. Any dog that my factory returns must implement this Java interface, so for the purposes of this example, I’ll keep this interface very simple. I'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 ();
}
Back to top

The concrete Dog classes

Next, I'll define a few concrete classes that implement my Dog interface. Keeping with our simple interface, each class implements the speak method, but implements it in a slightly different way that is appropriate to 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 my 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 my base class, in this case, my Dog interface.

Back to top

The Java Factory class

Next I’ll define my 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 that depends 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 my Java factory method states that I’ll 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 Dog interface.

Also, it’s 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.

Back to top

The Java Factory pattern example driver program

Now that I’ve created my dog factory, the Dog interface, and all of the dog sub-types, I’ll create a “driver” program named JavaFactoryPatternExample to test the Dog factory. This driver class demonstrates how to get different types of dogs from the factory:

/**
 * A "driver" program to demonstrate my "dog factory".
 * @author alvin alexander, alvinalexander.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 my driver class, I create an instance of each type of dog (small, big, and working).

Back to top

Discussion

My intent here isn’t to get too deep into the theory behind the Factory Pattern, but instead to demonstrate the factory pattern with some example 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.

Back to top

Download my example source code

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

Back to top
Permalink

this pattern example help me a lots. Thankyou verymuch.

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!

Permalink

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

Permalink

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

Permalink

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

Permalink

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

cK

Permalink

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

Permalink

Great many thanks to the author: Alvin.

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

Permalink

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

Thanks a lot

Permalink

thanks, it's very easy for understanding.

Permalink

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

Permalink

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

Permalink

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

Permalink

Clean, no-nonsense example. Simple and gets the point straight across. Thumbs up for the pagelayout layout and the ToC at right hand top corner.

Add new comment

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

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.