The Factory Pattern: Decoupled Object Creation
The Factory pattern creates objects without exposing instantiation logic to the caller, using a common interface to decouple application code from concrete classes 🏭.
class S3Storage:
def save(self, name): return f"Saved {name} to AWS S3 ☁️"
class LocalStorage:
def save(self, name): return f"Saved {name} to local disk 💾"
class StorageFactory:
@staticmethod
def get_storage(backend: str):
if backend == "cloud": return S3Storage()
return LocalStorage()
store = StorageFactory.get_storage("cloud")
print(store.save("report.pdf"))
# 117. The Factory Pattern: Decoupled Object Creation The Factory pattern creates objects without exposing instantiation logic to the caller, using a common interface to decouple application code from concrete classes 🏭. ```python class S3Storage: def save(self, name): return f"Saved {name} to AWS S3 ☁️" class LocalStorage: def save(self, name): return f"Saved {name} to local disk 💾" class StorageFactory: @staticmethod def get_storage(backend: str): if backend == "cloud": return S3Storage() return LocalStorage() store = StorageFactory.get_storage("cloud") print(store.save("report.pdf")) ``` When you need to switch storage from local disk to S3 or GCP, you only modify the factory instead of searching and rewriting 50 different call-sites! 🏭 --- ### Question What is the primary architectural advantage of the Factory pattern? 🧠 - [ ] a. Decouples client business code from concrete class implementations 🏭 - [ ] b. Forces all objects to share a single CPU thread - [ ] c. Eliminates the need for class constructors - [ ] d. Stores instances in the Linux swap partition --- ### Challenge Write a factory `NotifierFactory.create(mode)` returning `'EmailNotifier'` if `mode == 'email'` else `'SMSNotifier'`. Print `NotifierFactory.create('email')`. 🎯 <details> <summary>Solution</summary> ```python class NotifierFactory: @staticmethod def create(mode): return "EmailNotifier" if mode == "email" else "SMSNotifier" print(NotifierFactory.create("email")) ``` </details>