How to Build Factory Class in Python


In object-oriented design and programming, the Factory pattern is a design pattern used to create objects without specifying the exact class of object that will be created. The Factory method pattern deals with the problem of creating objects without specifying the exact class of object that will be created. Instead, it refers to the creation through the use of a common interface.

In Python, the Factory pattern can be implemented in various ways. One way to link it with class methods is by using a class method as a factory for creating instances of that class.

Here’s an example to demonstrate this concept:

class Animal:
_types = {}

@classmethod
def register_type(cls, animal_type, animal_cls):
cls._types[animal_type] = animal_cls

@classmethod
def create(cls, animal_type, *args, **kwargs):
if animal_type not in cls._types:
raise ValueError(f"Animal type {animal_type} not recognized.")
return cls._types[animal_type](*args, **kwargs)

class Cat(Animal):
def __init__(self, name):
self.name = name

def speak(self):
return f"{self.name} says Meow!"

class Dog(Animal):
def __init__(self, name):
self.name = name

def speak(self):
return f"{self.name} says Woof!"

# Registering the animal types with the factory
Animal.register_type("cat", Cat)
Animal.register_type("dog", Dog)

# Using the factory method to create instances
cat = Animal.create("cat", "Whiskers")
dog = Animal.create("dog", "Buddy")

print(cat.speak()) # Whiskers says Meow!
print(dog.speak()) # Buddy says Woof!

In this example:

  1. Animal class serves as a factory. It has a dictionary _types to keep track of the registered animal types.
  2. register_type is a class method used to register new animal types.
  3. create is the factory method. It’s a class method that creates an instance of the appropriate type.
  4. Cat and Dog are concrete implementations of the Animal type.
  5. We register these types with the Animal factory, and then use the create method to produce instances.

The relationship between factory class and class method here is that the class method provides a convenient and encapsulated way to create instances of the class without directly invoking the constructors of the concrete implementations. This can make code more flexible and easier to maintain because the exact classes of the objects and the logic for their creation can be kept separate from the rest of the application.

More about python class method can be found here


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC