Introduction to the Factory Method Pattern

Introduction to the Factory Method Pattern

Welcome back! So far, you’ve learned about the Singleton Pattern and have seen how it ensures a class has only one instance with a global access point. Now, we’re moving on to another essential creational design pattern: the Factory Method Pattern. This pattern is all about creating objects in a much more flexible way than direct instantiation. You’ll learn how to implement your own factory methods to instantiate different types of objects and see how this pattern allows your code to handle new object types with ease.

Understanding the Factory Method Pattern

The Factory Method Pattern is a creational design pattern that provides an interface for creating an object but allows subclasses to alter the type of objects that will be created. This pattern promotes loose coupling by eliminating the need to specify the exact class of the object that will be created. Instead, the instantiation is handled by subclasses.

You should consider using the Factory Method Pattern when object creation requires conditional logic, when working with large class hierarchies, or when developing frameworks and libraries that need to allow users to extend and customize object creation.

Implementing a Factory Method

To understand how the Factory Method Pattern is implemented, let's break the process down into intermediate steps.

Step 1: Define an Abstract Base Class

First, define an abstract base class Document with an abstract method open. This class will serve as the template for different types of documents.

Python
from abc import ABC, abstractmethod

class Document(ABC):
    @abstractmethod
    def open(self):
        pass

Step 2: Create Concrete Subclasses

Next, create concrete subclasses of Document. Each subclass will implement the open method. For example, let's define WordDocument and ExcelDocument.

class WordDocument(Document):
    def open(self):
        print("Opening Word document.")

class ExcelDocument(Document):
    def open(self):
        print("Opening Excel document.")
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal