The Factory Design Pattern is a creational pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code. The creation of the object is done in a separate method, which can be overridden by subclasses to change the class of objects that will be created.
- Encapsulation: The pattern encapsulates the instantiation process.
- Substitution: Subclasses can specify the type of objects to be created.
- Flexibility: It provides flexibility in terms of object creation.
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def operation(self) -> str:
pass
class ConcreteProductA(Product):
def operation(self) -> str:
return "Result of ConcreteProductA"
class ConcreteProductB(Product):
def operation(self) -> str:
return "Result of ConcreteProductB"
class Creator(ABC):
@abstractmethod
def factory_method(self) -> Product:
pass
def some_operation(self) -> str:
product = self.factory_method()
return f"Creator: The same creator's code has just worked with {product.operation()}"
class ConcreteCreatorA(Creator):
def factory_method(self) -> Product:
return ConcreteProductA()
class ConcreteCreatorB(Creator):
def factory_method(self) -> Product:
return ConcreteProductB()
def client_code(creator: Creator) -> None:
print(f"Client: I'm not aware of the creator's class, but it still works.\n"
f"{creator.some_operation()}")
if __name__ == "__main__":
print("App: Launched with the ConcreteCreatorA.")
client_code(ConcreteCreatorA())
print("\n")
print("App: Launched with the ConcreteCreatorB.")
client_code(ConcreteCreatorB())In this example, Creator is an abstract class with a factory method factory_method that returns a Product object. ConcreteCreatorA and ConcreteCreatorB are subclasses that override the factory_method to create instances of ConcreteProductA and ConcreteProductB, respectively.