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 instantiated1from abc import ABC, abstractmethod2 # Animal is abstract base class for all animals# Inheriting ABC marks it as abstract3class Animal(ABC): # @abstractmethod requires subclasses to implement # speak() must be defined in Dog, Cat, etc.4 @abstractmethod5 def speak(self) -> str: # pass is placeholder for abstract method6 pass7 # @classmethod receives class as first argument # Factory method returns an instance of the matching subclass8 @classmethod9 def create(cls, animal_type: str) -> "Animal": # Check which type to create10 if animal_type == "dog": # Return Dog instance11 return Dog()12 elif animal_type == "cat": # Return Cat instance13 return Cat() # Unknown type raises error14 raise ValueError(f"Unknown: {animal_type}")15 # Dog is concrete implementation of Animal# Must implement all abstract methods16class Dog(Animal): # Implements speak() from Animal17 def speak(self) -> str:18 return "Woof!"19 # Cat is another concrete implementation20class Cat(Animal): # Implements speak() from Animal21 def speak(self) -> str:22 return "Meow!"23 # Use factory to create Dog without knowing class# Animal.create() hides which class is created24animal = Animal.create("dog")# Call speak() on created animal# Prints "Woof!" because it's a Dog25print(animal.speak())Output
Woof!
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