Skip to main content

38. Factory Pattern

The Factory pattern provides a way to create objects without specifying the exact class.


Example

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

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

def animal_factory(kind):
if kind == "dog": return Dog()
if kind == "cat": return Cat()
raise ValueError("Unknown animal")

a = animal_factory("dog")
print(a.speak())

Wrap-Up

Factories decouple object creation from usage.