Factory Method Pattern

The Factory Method pattern defines an interface for creating an object, but lets the subclasses decide which class to instantiate. The Factory Method lets a class defer instantiation to subclasses, which is useful for constructing individual objects for a specific purpose without the requester knowing the specific class being instantiated. This enables you to introduce new classes without modifying the code because the new class implements only the interface so it can be used by the client. You create a new factory class to create the new class, and the factory class implements the factory interface. 

UML Representation


The following lists the benefits of using the Factory Method pattern:
  • Eliminates the need to bind application classes into your code. The code deals only with the interface, so you can work with any classes that implement that interface.
  • Enables the subclasses to provide an extended version of an object, because creating an object inside a class is more flexible than creating the object directly in the client.

When to Use

You should use the Factory Method pattern when:
  • A class cannot anticipate the class of objects it must create. 
  • A class wants its subclasses to specify the objects it creates.
  • Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.