Factory Method

Also known as virtual constructor.

Problem

A class or framework can't anticipate the kind of objects it must create.

Solution

Structure

Behavior

Discussion

All products implement a common interface:

interface Product {...}

The creator class postpones decisions about what types of products are created by using a virtual constructor/abstract factory method:

abstract class Creator {
   //virtual constructor:
   abstract Product makeProduct();
   // etc.
}

A concrete creator replaces the abstract factory method with a concrete factory method. In this example the details of the concrete product are hidden as a private inner class:

class ConcreteCreator extends Creator {
   private class ConcreteProduct implements Product {...}
   Product makeProduct() { return new ConcreteProduct(); }
}

Generic Constructors

In C++ template parameters can represent constructors as well as classes, so generic constructors can be used to delay decisions about the types of products to create:

template<typename Product>
class Creator
{
public:
   // generic constructor:
   Product* makeProduct() { return new Product(); }
};

In this case there is no need to introduce an abstract Product base class. Here is how a client creates a concrete product:

Creator<ConcreteProduct> creator;
ConcreteProduct* p = creator.makeProduct();

Example:

Java is fond of factory methods. For example, there are many types of XML Dom parsers. To hide the details of which parser is being used, Java uses the factory methods:

String xmlFile = "mydoc.xml";
// obtain parser factory:
DocumentBuilderFactory factory =
   DocumentBuilderFactory.newInstance();
//obtain parser:
DocumentBuilder builder =
   factory.newDocumentBuilder();
// parse an xml document into a DOM tree:
Document doc =
   builder.parse(new File(xmlFile));