Welcome to our comprehensive guide on the Factory Pattern in Python! This tutorial is designed to be accessible for both beginners and intermediates, so let's dive right in! 🐠
The Factory Pattern is a creational design pattern that provides an easy way to create objects without specifying the exact class of object that will be created. It's like a factory that produces objects, but you don't need to know the specific details of each product it makes.
The Factory Method is a simple implementation of the Factory Pattern. It's a method that returns a product object.
class Product:
pass
class ConcreteProductA(Product):
def __init__(self):
self.name = 'Product A'
class ConcreteProductB(Product):
def __init__(self):
self.name = 'Product B'
class Creator:
@staticmethod
def factory_method(product_type):
if product_type == 'A':
return ConcreteProductA()
elif product_type == 'B':
return ConcreteProductB()
else:
raise ValueError(f"Invalid product type: {product_type}")
creator = Creator()
product_a = creator.factory_method('A')
product_b = creator.factory_method('B')
print(product_a.name) # Output: Product A
print(product_b.name) # Output: Product BThe Abstract Factory Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
from abc import ABC, abstractmethod
class ProductA:
@abstractmethod
def operation_A(self):
pass
class ConcreteProductA1(ProductA):
def operation_A(self):
print('ConcreteProductA1: Operation A1')
class ConcreteProductA2(ProductA):
def operation_A(self):
print('ConcreteProductA2: Operation A2')
class ProductB:
@abstractmethod
def operation_B(self):
pass
class ConcreteProductB1(ProductB):
def operation_B(self):
print('ConcreteProductB1: Operation B1')
class ConcreteProductB2(ProductB):
def operation_B(self):
print('ConcreteProductB2: Operation B2')
class AbstractFactory(ABC):
@abstractmethod
def create_product_A(self):
pass
@abstractmethod
def create_product_B(self):
pass
class ConcreteFactory1(AbstractFactory):
def create_product_A(self):
return ConcreteProductA1()
def create_product_B(self):
return ConcreteProductB1()
class ConcreteFactory2(AbstractFactory):
def create_product_A(self):
return ConcreteProductA2()
def create_product_B(self):
return ConcreteProductB2()
creator = ConcreteFactory1()
product_a = creator.create_product_A()
product_b = creator.create_product_B()
print(product_a.operation_A()) # Output: ConcreteProductA1: Operation A1
print(product_b.operation_B()) # Output: ConcreteProductB1: Operation B1
creator = ConcreteFactory2()
product_a = creator.create_product_A()
product_b = creator.create_product_B()
print(product_a.operation_A()) # Output: ConcreteProductA2: Operation A2
print(product_b.operation_B()) # Output: ConcreteProductB2: Operation B2What is the main purpose of the Factory Pattern?
What is the difference between the Factory Method and the Abstract Factory Pattern?