Middle+
What is the Factory Method?
sobes.tech AI
Answer from AI
Factory Method is a creational design pattern that defines an interface for creating an object but allows subclasses to alter the type of objects that will be created. It encapsulates the object creation logic in a separate method, which is called by client code. This separates the code that uses the objects from the code that creates them.
Key components:
- Creator: Declares the factory method that returns an object of type Product. This class may have a default implementation of the factory method.
- Concrete Creator: Overrides the factory method to return an instance of a Concrete Product.
- Product: Defines the interface for objects created by the factory method.
- Concrete Product: Implements the Product interface.
Advantages:
- Reduces coupling between classes that use and create objects.
- Allows adding new product types without changing client code.
- Supports the Open/Closed Principle.
Example:
# Product interface
class Product:
def operation(self):
pass
# Concrete Product A
class ConcreteProductA(Product):
def operation(self):
return "Result of ConcreteProductA"
# Concrete Product B
class ConcreteProductB(Product):
def operation(self):
return "Result of ConcreteProductB"
# Creator interface
class Creator:
def factory_method(self):
pass
def some_operation(self):
# Creator usually contains logic that depends on Product objects.
# The specific Product is created via the factory method.
product = self.factory_method()
# Call the Product's operation
result = f"Creator: Same logic works with {product.operation()}"
return result
# Concrete Creator A overrides the factory method to create ConcreteProductA
class ConcreteCreatorA(Creator):
def factory_method(self):
return ConcreteProductA()
# Concrete Creator B overrides the factory method to create ConcreteProductB
class ConcreteCreatorB(Creator):
def factory_method(self):
return ConcreteProductB()
# Client code
def client_code(creator):
print(f"Client: I don't know the class of the creator, but it still works.\n"
f"{creator.some_operation()}")
The Factory Method is often used when a class cannot anticipate the type of objects it needs to create or when it wants to delegate the responsibility of object creation to subclasses.