A Java Factory Pattern (Factory method) example

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

Sure. In this article I'll demonstrate a small-but-complete example of the Factory Pattern (also known as the “Factory Design Pattern” and “Factory Method”) 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 the 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 specific factory pattern example in Java.

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 ();
}

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.

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.

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

Discussion

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

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.