Factory Method Pattern in Python

Level 5454 keystrokes

This implements the Factory Method pattern. A classmethod creates instances without exposing creation logic to the client.

Python code

# Import ABC and abstractmethod for abstract classes
# With ABC, a class that has abstract methods can't be instantiated
1from abc import ABC, abstractmethod
2
# Animal is abstract base class for all animals
# Inheriting ABC marks it as abstract
3class Animal(ABC):
# @abstractmethod requires subclasses to implement
# speak() must be defined in Dog, Cat, etc.
4 @abstractmethod
5 def speak(self) -> str:
# pass is placeholder for abstract method
6 pass
7
# @classmethod receives class as first argument
# Factory method returns an instance of the matching subclass
8 @classmethod
9 def create(cls, animal_type: str) -> "Animal":
# Check which type to create
10 if animal_type == "dog":
# Return Dog instance
11 return Dog()
12 elif animal_type == "cat":
# Return Cat instance
13 return Cat()
# Unknown type raises error
14 raise ValueError(f"Unknown: {animal_type}")
15
# Dog is concrete implementation of Animal
# Must implement all abstract methods
16class Dog(Animal):
# Implements speak() from Animal
17 def speak(self) -> str:
18 return "Woof!"
19
# Cat is another concrete implementation
20class Cat(Animal):
# Implements speak() from Animal
21 def speak(self) -> str:
22 return "Meow!"
23
# Use factory to create Dog without knowing class
# Animal.create() hides which class is created
24animal = Animal.create("dog")
# Call speak() on created animal
# Prints "Woof!" because it's a Dog
25print(animal.speak())

Output

Woof!
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • "× 14
  • (× 13
  • )× 13
  • :× 11
  • =× 5
  • _× 4
  • -× 4
  • >× 4
  • ,× 2
  • !× 2

More Python examples at level 5

← Python typing practice