Extension: Factory Pattern

The Factory pattern provides a way to create objects without specifying their exact class at the call site. You ask a factory for an object, and the factory decides which class to instantiate.

The Problem Without Factory

# Without factory — caller must know every concrete class
animal_type = get_user_input()  # "dog" or "cat"
if animal_type == "dog": animal = Dog()
elif animal_type == "cat": animal = Cat()
# This if/elif must be repeated everywhere...

If you add a new animal type, you must find and update every place that has this if/elif chain. The Factory centralises this logic.

Factory Pattern

class AnimalFactory:
    @staticmethod
    def create(animal_type):
        if animal_type == "dog": return Dog()
        if animal_type == "cat": return Cat()
        raise ValueError(f"Unknown type: {animal_type}")
# Caller only needs to know the factory:
animal = AnimalFactory.create("dog")
  • A static method is ideal — no instance state needed
  • Always raise ValueError for unknown types — fail loudly
  • To add Bird, you only change AnimalFactory

Factory + Polymorphism

types = ["dog", "cat", "dog"]
animals = [AnimalFactory.create(t) for t in types]
for a in animals:
    print(a.speak())
Woof
Meow
Woof

The caller never directly references Dog or Cat. Factory decouples creation from usage.

Your Task

  1. Inside AnimalFactory.create(animal_type):
  2. If animal_type == "dog", return Dog()
  3. If animal_type == "cat", return Cat()
  4. Otherwise, raise ValueError(f"Unknown animal type: {animal_type}")
Section 1/4The Problem Without Factory

The Problem Without Factory

If you add a new animal type, you must find and update every place that has this if/elif chain. The Factory centralises this logic.

Extension: Factory Pattern

The Factory pattern provides a way to create objects without specifying their exact class at the call site. You ask a factory for an object, and the factory decides which class to instantiate.

The Problem Without Factory

# Without factory — caller must know every concrete class
animal_type = get_user_input()  # "dog" or "cat"
if animal_type == "dog": animal = Dog()
elif animal_type == "cat": animal = Cat()
# This if/elif must be repeated everywhere...

If you add a new animal type, you must find and update every place that has this if/elif chain. The Factory centralises this logic.

Output:

Click "Check" to run your code.