Factory Pattern
Low-Level Design: lesson 8 of 10
Ask for what you want; one place decides which class to build.
Lesson 8 of 10 · 4 min
Factory Pattern
Step 1 of 11
call sitesevery one knows a class
Scattered Van() calls hard-wire every caller to a concrete class.
The Idea
Scattered SomeClass() calls hard-wire every caller to a concrete type. A factory takes a key and returns an object honouring a shared interface. Choosing moves to one function, and unknown keys fail there with a clear message instead of anywhere.
Real-World Example
A car hire desk. You booked "estate, automatic" and you are handed whichever car in today's fleet meets that class. You never name a model, and the depot can retire one and buy another without telling you.
The Code
class Estate: seats, boot = 5, 550 # three products, one shared shape
class Van: seats, boot = 3, 3000
class Compact: seats, boot = 4, 300
FLEET = {"estate": Estate, "van": Van, "compact": Compact}
def hire(car_class): # callers name a class, never a constructor
if car_class not in FLEET:
raise ValueError("no such class: " + car_class)
return FLEET[car_class]()
car = hire("van")
print(type(car).__name__, car.seats, car.boot) # Van 3 3000
print(type(hire("estate")).__name__) # Estate
Your turn
What does this print?
class Cat:
def sound(self): return "meow"
class Cow:
def sound(self): return "moo"
MAKERS = {"cat": Cat, "cow": Cow}
def make(key): return MAKERS[key]()
print(make("cow").sound(), type(make("cat")).__name__)Mini quiz
1 / 3