Factory Method Pattern

This lesson discusses how derived classes can be given the responsibility of creating appropriate objects.

What is it ?

A factory produces goods, and a software factory produces objects. Usually, object creation in Java takes place like so:

SomeClass someClassObject = new SomeClass();

The problem with the above approach is that the code using the SomeClass's object, suddenly now becomes dependent on the concrete implementation of SomeClass. There's nothing wrong with using new to create objects but it comes with the baggage of tightly coupling our code to the concrete implementation class, which is a violation of code to an interface and not to an implementation.

Formally, the factory method is defined as providing an interface for object creation but delegating the actual instantiation of objects to subclasses.

Class Diagram

The class diagram consists of the following entities

  • Product
  • Concrete Product
  • Creator
  • Concrete Creator
Class Diagram
Class Diagram

Example

Continuing with our aircraft example scenario, let's assume we are trying to model the F-16 fighter jet. The client code needs to construct the engine object for the fighter jet and fly it. The naive implementation for the class would be something like below:

...