1.Factory and Abstract Factory
A Factory is a function that picks which class to instantiate based on input, so callers never write ClassName(...) directly. An Abstract Factory is a family of factories that each produce a matching set of related objects.
Key features
- Factory: one function or method that returns a concrete instance based on input, hiding the class name from the caller
- Abstract Factory: an interface with one creation method per product; each concrete factory implementation produces a matching family
- Both patterns exist so calling code depends on an interface (Notifier, Button) rather than a concrete class name
- Factory picks ONE product from a type; Abstract Factory picks a whole SET of related products that must stay consistent with each other
- Adding a new variant means adding one new factory/class, not editing every place the old ones were instantiated
Factory vs. Abstract Factory
- notifier_factory("email") — caller states intent, not a class name
- picks EmailNotifier — the factory owns the if/elif branching
- notifier.send(msg) — caller only ever sees the shared interface
Command
def notifier_factory(channel: str):
if channel == "email":
return EmailNotifier()
if channel == "sms":
return SmsNotifier()
raise ValueError(f"unknown channel: {channel}")
notifier = notifier_factory("email")
notifier.send("your order shipped")Factory centralizes "which class do I instantiate?" behind one function; Abstract Factory centralizes it for a whole family of related objects that must stay consistent with each other.