DEV Community

Cover image for Design Patterns: Factory Method
Shakil Hossain
Shakil Hossain

Posted on • Edited on

Design Patterns: Factory Method

Introduction

I am recently reading a book by Alexander Shvets called Dive Into Design Patterns. And he has broken down these complex patterns into very intuitive and simple terms with Diagrams, Pseudocode When to use them, How to use them, the pros and cons of the patterns, and also how it relates to other design patterns.

I encourage the readers to buy the book and most of the content of this article is based on the book. Here's the link if anyone wants to buy the book also there's a course available that is a little bit expensive but I think it's worth it.

Enough chit-chat, let's dive into the creational design patterns. And today we are gonna discuss the Factory Method pattern aka the starting point of all the creational patterns. So if you are an intermediate coder fasten your seat belt cause it is going to be an awesome journey and by the end of it you can apply this pattern to your code base and create a maintainable and efficient code base.

I will start the journey by quoting my mentor who quoted another famous programmer (forgot the name). It goes "Code is document and document is code." At least something like that.

If you know what is the Factory Method Creational Pattern then the good job you know. But for those poor sobs who don't know it, I will explain it anyway just for them because I am one of them.

Factory Method/Virtual Constructor

Factory Method is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. (Reference: Dive Into Design Patterns by Alexander Shvets)

This method requires us to avoid calling object constructors directly. And instead, use a special method to create objects for us. This method is called Factory Method. Hence the name of this pattern is Factory Method.

From here on we will call the objects products. And the class the factory method resides in we will call it Factory Class. The factory produces products using special behavior (that is our factory method). Also we will call Factory Class with the name Creator Class. Both of them have two types Abstract and Concrete.

The Factory/Creator Class can be a interface and different types of sub classes can implement this interface and define the method of producing a product in different ways. Also I want to mention that the creator class does not need to be an interface it can be a super class too. And any repeatable action that is applicable for all products can reside inside the Creator super class. But the creating products method must be abstract method that needs to be implemented on the other concrete creator sub classes and the return type will be the concrete product class type.

Structure

To illustrate what I mean here's a diagram:

Structure of Factory Method Pattern

  1. The product declares the interface, which is common to all objects and it is produced by the concrete creator sub class.

  2. Concrete Products are customized implementation of the product interface.

  3. The abstract/super creator class defines the factory method as abstract and the return type must be the product interface.

  4. Concrete Creators override the base factory class so it returns a different type of products.

Use Cases:

  1. Use the Factory Method when you don’t know beforehand the
    exact types and dependencies of the objects your code should
    work with.

  2. Use the Factory Method when you want to provide users of
    your library or framework with a way to extend its internal
    components.

  3. Use the Factory Method when you want to save system
    resources by reusing existing objects instead of rebuilding
    them each time.

How To Implement:

  1. Make all products follow the same interface. This interface should declare methods that make sense in every product.

  2. Add an empty factory method inside the creator class. The
    return type of the method should match the common product
    interface.

  3. In the creator’s code find all references to product constructors. One by one, replace them with calls to the factory method, while extracting the product creation code into the factory method.

  4. Now, create a set of creator sub classes for each type of product listed in the factory method. Override the factory method in the sub classes and extract the appropriate bits of construction code from the base method.

  5. If there are too many product types and it doesn’t make sense to create sub classes for all of them, you can reuse the control parameter from the base class in sub classes.

  6. If, after all of the extractions, the base factory method has become empty, you can make it abstract. If there’s something left, you can make it a default behavior of the method.

Pros:

  1. You avoid tight coupling between the creator and the concrete products.

  2. Single Responsibility Principle. You can move the product creation code into one place in the program, making the code easier to support.

  3. Open/Closed Principle. You can introduce new types of products into the program without breaking existing client code.

Cons:

  1. The code may become more complicated since you need to introduce a lot of new sub classes to implement the pattern. The best case scenario is when you’re introducing the pattern into an existing hierarchy of creator classes.

Conclusion

In this article I tried to break down the Factory Method design patterns. And also discussed about what it is and how it is done and when it is useful. One thing I want to let the readers know if you have a very small code base this pattern may introduce certain complexity that should be ignored but for mid size to big projects if you want to make you code maintainable and well documented (remember the quote?) it can save a lot of time and improve the code readability and extensibility of your product.

Top comments (0)