How to Implement the Factory Design Pattern

120 views

How to Implement the Factory Design Pattern

How to Implement the Factory Design Pattern

What is the Factory design pattern, and how can it be implemented in Python?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

Factory pattern defines an interface for creating objects and allows subclasses to alter the object type created.

Code:

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

class AnimalFactory:
    def create_animal(self, animal_type):
        if animal_type == "dog":
            return Dog()
        elif animal_type == "cat":
            return Cat()
        else:
            return None

factory = AnimalFactory()
animal = factory.create_animal("dog")
print(animal.speak())  # Output: Woof!

solveurit24@gmail.com Changed status to publish February 20, 2025
0