Problem Statement
When object creation is scattered and uncontrolled, the code becomes hard to maintain and extend. This leads to duplicated code, tight coupling, and difficulty in managing complex object setups.
This diagram shows how client code requests object creation from a centralized factory or creator, which then produces the desired object.
### Before: Direct instantiation scattered in code class Car: def __init__(self, model): self.model = model car1 = Car('Sedan') car2 = Car('SUV') ### After: Using Factory pattern to manage creation class Car: def __init__(self, model): self.model = model class CarFactory: @staticmethod def create_car(car_type): if car_type == 'Sedan': return Car('Sedan') elif car_type == 'SUV': return Car('SUV') else: raise ValueError('Unknown car type') car1 = CarFactory.create_car('Sedan') car2 = CarFactory.create_car('SUV')
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
obj1 = Singleton()
obj2 = Singleton()
print(obj1 is obj2)class Builder:
def __init__(self):
self.product = Product()
def build_part(self):
self.product.add('part')
def get_product(self):
return self.product
builder = Builder()
builder.build_part()
product = builder.get_product()
print(product.parts)new or constructors?Pass the test and this pattern moves unknown