Design Patterns 2 - Factory Pattern

Feb 9, 2021 00:00 · 298 words · 2 minute read DesignPatterns

Factory Pattern enhance loose coupling in your code.

1. What is Factory Pattern?

The Factory Pattern is a way to provide factory interfaces for creating objects in object-oriented programming. These interfaces define the generic structure not the actual objects. The initialization of the real objects are left for more specific subclasses. In the following example, we created three classes Animal, Dog and Cat with the same method name. The Animal class is the superclass which only provides the interface through abstractmethod. Dog and Cat are subclasses. The AnimalFactory class is used to combine those three classes together.

2. Code example

The UML digram of this example is as follow:

from abc import ABC, abstractmethod

# Abstract class
class Animal(ABC):
    @abstractmethod
    def calculate_speed(self):
        pass

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

    def calculate_speed(self):
        return self.height * 10

class Cat(Animal):
    def __init__(self, height):
        self.height = height
        
    def calculate_speed(self):
        return self.height * 2
    
class AnimalFactory:
    def get_animal(self, name):
        height = input("Enter the height of the animal: ")
        if name == 'dog':
            return Dog(float(height))
        elif name == 'cat':
            return Cat(int(height))
        
def speed_client():
    Animal_factory = AnimalFactory()
    animal_name = input("Enter the name of the animal: ")

    speed = Animal_factory.get_animal(animal_name)

    print(f"The type of object created: {type(speed)}")
    print(f"The speed of the {animal_name} is: {speed.calculate_speed()}")
speed_client()
# Output:
    Enter the name of the animal:  dog
    Enter the height of the animal:  2
    The type of object created: <class '__main__.Dog'>
    The speed of the dog is: 20.0

3. Code explanation

In above code, @abstractmethod decorator is used to provide an interface method. Dog and Cat subclasses can have their own different methods with the same method name but different contents.

The Factory Pattern can create objects without specifying the exact class required to create the particular objects, which decouples the code and enhances its reusability.

Reference:

tweet Share

Related Articles