Design Patterns — Fast Recall (Python)
Factory — decide the class at runtime
- What: move object creation behind a function/method so callers don't hardcode concrete classes.
- Why / when: the concrete type depends on input, config, or environment (e.g. `parser_for('json')`), and you want to add new types without touching callers.
- Key benefit: creation logic lives in one place — new type = one new branch/registry entry.
- Python truth: skip the class hierarchy — a `dict` registry of `{key: cls}` is the idiomatic factory.
1class Dog: speak = lambda self: "woof"
2class Cat: speak = lambda self: "meow"
3
4REGISTRY = {"dog": Dog, "cat": Cat} # the "factory"
5
6def make_animal(kind):
7 return REGISTRY[kind]() # caller never names the class
8
9print(make_animal("cat").speak()) # meow