Factory Pattern
Creating an object looks like the simplest line of code there is: EmailSender(). It stops being simple when the
class to create depends on something you only know at runtime, such as a channel name in a message, a provider
in a config file, or the game the player picked. Then an if/elif that chooses a constructor appears wherever
objects are made, and every caller ends up knowing the name and the constructor arguments of every concrete
class.
A factory moves the decision "which class, built how" into one place. Callers ask for "a sender for SMS" and
get back something that implements Sender, without ever naming SmsSender. There are three forms, from light to
heavy: the simple factory, the factory method and the abstract factory. Most interview problems need
only the first.
🏭 In one sentence: put the decision of which concrete class to create, and how to construct it, behind one method, so the rest of the code asks for an interface and never names the concrete classes.
The Problem It Solves
Here is an alert service that sends a message on the channel a user picked. The senders already share a
send(user, text) method, so the sending is fine. The trouble is the creating.
class AlertService:
def notify(self, user: User, channel: str, text: str) -> None:
if channel == "email":
sender = EmailSender(host="smtp.internal", port=587)
elif channel == "sms":
sender = SmsSender(api_key=os.environ["SMS_KEY"], sender_id="ALERTS")
elif channel == "push":
sender = PushSender(app_id="com.example.app")
else:
raise ValueError(f"unknown channel {channel}")
sender.send(user, text)
Now imagine the same block in DigestService and in PasswordResetService, because they also send messages.
The creation logic is duplicated. Three services know that SMS needs an API key from the environment. When the SMS provider adds a region parameter, you edit three places and hope you found them all.
Every caller depends on every concrete class. Each service imports EmailSender, SmsSender and
PushSender. Adding a Slack channel means editing all three services, even though none of them cares how Slack
works.
It can't be tested without the real thing. AlertService builds its own senders, so a test has no way to
hand it a fake. Running the test either sends a real SMS or crashes because SMS_KEY is not set.
Wiring is mixed with business logic. Hosts, ports and keys sit next to the rule "send the alert". Reading the method, it is hard to see what it actually decides.
⚠️ The smell to look for:
if/elifon a type or name whose branches each call a different constructor, especially when the same chain appears in several classes. Strategy fixes branches that do different things; a factory fixes branches that create different things.