The Factory Method Design Pattern

What is Factory Method Design Pattern?

Gang of Four categorizes the factory method design pattern as a creational pattern since it deals with object creation.  This pattern enforces the loose coupling and encapsulation principles in object-oriented programming. This pattern applies in situations where there are sub-classes involved, and the creation of those becomes complex with the system execution. According to the GoF factory method has following standard definition,

“An interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses”

In simpler words, object creation is handed over to a separate entity via an interface. This entity is called the factory, and it contains the object creation code with the help of an interface or an abstract class to create the suitable object from various class implementations. Only sub-classes are responsible and decide which class to instantiate at runtime.

This pattern is also called as a ‘virtual constructor’ because the creation logic is hidden from the client and only an interface or abstract class will expose the suitable factory method to the client. Thus, the interface allows separating the object creation code from the external world.

Here client uses the factory to create object instances.

 

Factory method pattern
Factory method pattern

Problems solved by Factory Method

  • Complex object creation, especially within several layers of class hierarchy
  • Usage of new() operator, causing complexity, duplication and inflexibility issues in application code
  • When the client is unauthorized to access in-detail class implementations

When to Use the Factory Design Pattern

  • The internal implementation is hidden from the client application or when a class could not foresee the type of objects it is obliged to create
    • There are times when the main application or framework is unaware of the run-time object creations. Only interfaces or abstract classes are visible to request the service. In this situation, factory class should come to the scenery and support the object creation via the abstract method.
  • a system needs to be independent of various object creation procedures
  • there are different approaches of implementations to one class and the required implementation needs to be selected at runtime
  • parent class decides to delegate the suitable object creation to subclasses depending on the provided data
  • Programming to the interface is strictly enforced in an application, using new() operator would be a fatal issue which tends to create inflexible and unmaintainable code.
  • An application requires loose coupling, and encapsulation principle build within the code

 How Factory Method Design Pattern Works

Why do we need to introduce a factory?

Since the application is unaware of internal implementations of each subclass and only run-time will decide which class implementation to instantiate and use of new() to direct object instantiation each time will cause performance overhead with inflexibility in the system.

How the pattern eliminates the problem?

Use a common interface or an abstract class to obtain required methods that are to be used in factory class

Factory

Contains the separate object creation logic or the factory method to use when necessary. The client will call this method to get the required object at runtime

How to create the object?

Client delegates the object creation to the factory class specifying the required details at the run-time and the factory will instantiate the suitable new concrete object instance using the specific implementation of the sub-class via the factory pattern.

Let’s Learn from an Example

Let’s imagine a situation where you want to color roses for a party decoration. There is a bundle of white roses, and you need to make them red, yellow and pink according to the decoration style and place. In this situation, you can’t exactly say how many roses are needed in the yellow color or red color. The requirement is dependent on at the time of usage. So, we are unaware of the color of the rose at the beginning. Let’s apply the factory method design pattern to color these roses.

Class Diagram

The client specifies which rose is in need for the current decoration and the RodeFactory class input the clients’ request at run-time and creates the customized rose using the specific implementation of each subclass. So, that client doesn’t want to write hard-coded sub-class instantiation code in advance.

 

Factory method pattern class diagram
Factory method pattern class diagram

Class Diagram Components

  • Rose à Interface/Abstract Class: Contains the factory method to use in the factory class. This method is shared by all the sub-classes to implement the unique functionality required by the system
  • RedRose(Yellow/Pink) àConcrete Class: These concrete subclasses override the abstract methods included in the interface with their customized code
  • RoseFactory à Factory Class: Uses the factory method to create the object instances. Factory method will be executed at this level to create unique instances depending on the request from the client
  • CreateRoseDemo à Client Class: Request the specific behavior from the application. The client is not aware of how to create the object instead client knows when to create the object.

Code Samples

Interface/Abstract Class

Interface which contains the abstract method to use by subclasses.

Rose.java

Concrete Class

Concrete subclasses which implement the interface with full implementation.

RedRose.java

YellowRose.java

PinkRose.java

Factory / Creator

Create a Factory to generate an object of concrete class based on given information. Factory pattern encapsulates object creation logic, which makes it easy to change it later when you change how the object gets created, or you can even introduce a new object with just change in one class.

RoseFactory.java

Client

The application which requests the object to fulfill the decoration requirement

CreateRosedemo.java

Some Examples from Java World

We can find many occurrences of factory method design pattern inside the Java Development Kit. Those can be listed as below,

  • valueOf() – This is the most popular example from the JDK which is a part of String and Wrapper classes. It is used to convert between String and other primitive data types
  • text.NumberFormat – Specifies the abstract method collection for all number formatting and parsing functions.

Apart from those getInstance(), newInstance(), getType() are few other JDK factory methods which use this design pattern.

Advantage of Factory Design Pattern

  • Remove the code duplication using the factory class and method
  • Subclass implementations are independent of application clients, hence enforce flexibility, maintainability, and testability
  • Eliminate many run-time errors due to service delegation to the factory class
  • Maintain the code consistency through consolidating object creation mechanism within the factory class.
  • Encourage the programming to interface principle ensuring the code quality of the system

 

Drawbacks or Consequences of Factory Method Design Pattern

  • There might be many different factors to include when selecting the appropriate subclass to create instances at runtime which results in untidy conditional statements
  • If a class does not include in a parent-child class hierarchy or don’t implement the interface, it cannot be used within the factory class and not applicable in factory method pattern
  • It’s difficult to hook to already existing classes
  • Sometimes makes the code complex and challenging to read since most code contains the abstractions

7 thoughts to “The Factory Method Design Pattern”

  1. Its a great example, bu I have a question. Do we really need to create an insance of factory class? JDK claases like Calendar,Wrapper classes and String exposed these object creation methods as static methods.

    1. To answer your question, we don’t really need to use the new operator here to create the factory. We could create the instance of factory by having a static factory method. But it is important to understand that factory method and static factory method are two different design patterns as described in Effective Java (2nd Edition) [Gamma95, p. 107]. In this simple example that i have described above, i don’t see gaining anything by creating a static factory method but that would introduce another pattern into the tutorial.
      Now looking at the examples that you have given

      • valueOf —Returns an instance that has, loosely speaking, the same value as its parameters. Such static factories are effectively type-conversion methods.
      • Calendar.getInstance() – The Calendar returned is based on the current time in the default time zone with the default locale. This makes it easier to create the Calendar. It does not return a singleton.

Leave a Reply