How to Use Factory Pattern in Python

Fariba Laiq Feb 02, 2024
  1. Implement the Factory Method in Python
  2. Advantages of the Factory Method in Python
  3. Disadvantages of the Factory Method in Python
How to Use Factory Pattern in Python

Factory design pattern lies under the creational design pattern category. Creational design patterns provide many techniques for object creation which results in more code reusability and flexibility.

The factory method is a method for creating objects without specifying their concrete class.

It provides abstraction and polymorphism in a way that a single parent class (abstract class or the interface) defines the generic structure of objects, and the sub-class provides the complete implementation to instantiate the object.

Implement the Factory Method in Python

In the following code, abc is a package that stands for Abstract Base Class from which we have imported the ABCMeta (to declare an abstract class) and abstractstaticmethod (to declare an abstract static method).

We have defined a generic abstract base class named Person, having an abstract static method person_type().

The concrete derived class will implement this method. Then we have defined two derived classes from Person named Student and Teacher. Both classes implement the abstract static method person_type() as per their needs.

We have declared the Factory Method PersonFactory responsible for creating the objects of a Person (Student or a Teacher) at run time according to the input choice of the user.

This class has a static method, build_person(), that takes the person type as an argument and constructs the required object with their names (Student’s name or Teacher’s name).

Example Code:

# Python 3.x
from abc import ABCMeta, abstractstaticmethod


class Person(metaclass=ABCMeta):
    @abstractstaticmethod
    def person_type():
        pass


class Student(Person):
    def __init__(self, name):
        self.name = name
        print("Student Created:", name)

    def person_type(self):
        print("Student")


class Teacher(Person):
    def __init__(self, name):
        self.name = name
        print("Teacher Created:", name)

    def person_type(self):
        print("Teacher")


class PersonFactory:
    @staticmethod
    def build_person(person_type):
        if person_type == "Student":
            name = input("Enter Student's name: ")
            return Student(name)
        if person_type == "Teacher":
            name = input("Enter Teacher's name: ")
            return Teacher(name)


if __name__ == "__main__":
    choice = input("Enter the Person type to create: ")
    obj = PersonFactory.build_person(choice)
    obj.person_type()

Output:

#Python 3.x
Enter the Person type to create: Teacher
Enter Teacher's name: Jhon
Teacher Created: Jhon
Teacher

Advantages of the Factory Method in Python

  • It promotes loose coupling in the code.
  • It is easy to modify the code to instantiate new objects having slightly different characteristics without disturbing the current code.
  • It promotes abstraction and polymorphism in the code.

Disadvantages of the Factory Method in Python

  • We can only use it where the objects belong from the same category having slightly different features.
  • The factory design pattern increases the total number of classes in the code.
  • It reduces the readability of the code because the implementation is hidden due to abstraction.
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn