In this lesson, you will learn how to abstract the object instantiation process using the Factory Pattern to decouple your code from specific class implementations.
The Problem with Direct Instantiation
Usually, when you need an object, you call a class constructor directly: my_obj = ConcreteClass(). The downside is that your calling code becomes tightly coupled to that specific class. If you ever need to change the type of object being created—perhaps because of a configuration change or a runtime condition—you have to hunt down every place you called that constructor and update your code.
The Factory Solution
The Factory Pattern introduces a "factory" (a function or a separate class) that acts as the sole gatekeeper for object creation. Instead of the client code deciding which class to instantiate, it asks the factory for an object. The factory decides the specific type based on the input provided.
Consider a system that generates different types of notification objects:
class EmailNotification:
def send(self, msg): print(f"Email: {msg}")
class SMSNotification:
def send(self, msg): print(f"SMS: {msg}")
def notification_factory(method: str):
factories = {
"email": EmailNotification,
"sms": SMSNotification
}
# Return an instance without the caller knowing the class name
return factories.get(method)()
# Usage
notifier = notification_factory("email")
notifier.send("Hello Factory!")
Why Use This?
By using notification_factory, your main application logic remains "blind" to the existence of EmailNotification or SMSNotification. If you decide to add a PushNotification class later, you only update the factory. Your business logic remains untouched, which makes your system significantly easier to maintain and extend. This technique is particularly powerful when paired with your knowledge of Defining Interfaces with Abstract Base Classes, ensuring that every object returned by the factory adheres to a consistent interface (like a send method).
Key Takeaway: The Factory Pattern shifts the responsibility of object creation away from the client code, allowing you to swap or extend object types without modifying the logic that uses them.