Factory Patterns

Up Java Resources

Written by Algis Rudys and Stephen Huey

What do you do when you'd rather let a subclass decide which class of object to instantiate? Use the Factory Pattern!

The Factory Pattern, called Abstract Factory in the Design Patterns book (see page 87) is used to facilitate class instantiation by some client of the class being instantiated. In the Abstract Factory pattern, a special class, called a factory, is created whose sole purpose is to instantiate instances of a class.

There are two reasons one might want to do this. The first is that the factory is an object instance, which means it can be passed as an argument to a method. This allows an extra level of indirection in creating objects and passing them as parameters.

The second reason has to do with the pattern's name, Abstract Factory. It gets this name because the factory class itself is generally an abstract class. The concrete subclass of the abstract factory actually decides what to instantiate. For instance, if you want to instantiate a concrete subclass of abstract class Foo, you use a subclass of FooFactory. Subclasses of Foo are WhiteFoo, BlackFoo, and GreenFoo, and subclasses WhiteFooFactory, BlackFooFactory, and GreenFooFactory of FooFactory generate the appropriate object type. The caller needn't know the concrete instance of the factory, only that it generates instances of Foo.

The following image from Design Patterns illustrates this. Client is a class that uses AbstractProductA and AbstractProductB. Not caring which concrete classes it uses, Client keeps an AbstractFactory, which might be either ConcreteFactory1 or ConcreteFactory2 (again Client doesn't care), generating either ProductA1 and ProductB1 or ProductA2 and ProductB2, respectively.

The Factory Method pattern (see page 107 of Design Patterns) refers to a similar design pattern, wherein instead of being in a separate class, the factory functionality is within a method of the client class itself. The client class can be subclassed to determine which concrete subclass of the product is actually instantiated. Out in the real world, the lines probably blur when developers implement either or both of them.

For more info, see http://www.research.umbc.edu/~tarr/cs491/lectures/Factory-2pp.pdf

Here's the Maze Game code: http://www.cecs.csulb.edu/~tayek/morePatterns/#Factory

Images and the Maze example from this page and the two links come from the Design Patterns book.