Factory Pattern Under 1 minute - Software Design Pattern

1 min read

❓ Problem:
You want to create objects without knowing their exact class or logic.
🧠 Analogy:
Think of a restaurant where you say “I want a sandwich” and the kitchen (factory) decides whether to make a veg or non-veg sandwich.
✅ Advantages:
Centralized object creation
Easy to introduce new types (add class, update factory)
Reduces code duplication
⚠️ Pitfalls:
Logic may grow messy if too many conditions are hardcoded
If overused, can make code unnecessarily complex
class Notification:
def send(self):
pass
class Email(Notification):
def send(self):
print("Sending Email")
class SMS(Notification):
def send(self):
print("Sending SMS")
def notification_factory(type_):
if type_ == "email":
return Email()
elif type_ == "sms":
return SMS()
else:
raise ValueError("Unknown type")
notif = notification_factory("email")
notif.send() # Sending Email
In larger apps, you can even use reflection or registration instead of if-else
.
0
Subscribe to my newsletter
Read articles from Rahul Kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
creational-patternactory-methodFactory Design Patternsoftware design patternsObject Oriented Programmingdesign principlesabstractionencapsulationloose couplingmaintainabilityscalabilityExtensibility#CodeReuse software architectureJavaScript
Written by
