Bird
Raised Fist0
LLDsystem_design~7 mins

Why creational patterns manage object creation in LLD - Why This Architecture

Choose your learning style10 modes available
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.
Solution
Creational patterns centralize and abstract the process of creating objects. They provide flexible ways to instantiate objects, allowing changes in creation logic without affecting the rest of the code.
Architecture
Client Code
→Creator/Factory
↓
Product/Object
Product/Object

This diagram shows how client code requests object creation from a centralized factory or creator, which then produces the desired object.

Trade-offs
✓ Pros
→
Reduces code duplication by centralizing object creation logic.
→
Improves code flexibility by decoupling object creation from usage.
→
Makes it easier to manage complex creation processes or configurations.
→
Supports changing object types without modifying client code.
✗ Cons
→
Adds an extra layer of abstraction, which can increase complexity for simple cases.
→
May introduce more classes or interfaces, increasing codebase size.
→
Improper use can lead to over-engineering when simple instantiation suffices.
Use when object creation is complex, involves multiple steps, or when the system needs to support different types of objects dynamically.
Avoid when object creation is straightforward and unlikely to change, especially in small or simple applications.
Real World Examples
Amazon
Uses factory patterns to create different types of payment processors dynamically based on user selection.
Netflix
Applies builder patterns to construct complex streaming session objects with multiple configuration options.
Uber
Employs singleton and factory patterns to manage shared resources like location services and ride request handlers.
Code Example
The before code creates Car objects directly wherever needed, causing duplication and tight coupling. The after code centralizes creation in CarFactory, making it easier to manage and extend car types without changing client code.
LLD
### 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')
OutputSuccess
Alternatives
Direct Instantiation
Objects are created directly using constructors without abstraction.
Use when: When object creation is simple and unlikely to change.
Prototype Pattern
Creates new objects by cloning existing ones instead of building from scratch.
Use when: When object creation is costly and many similar objects are needed.
Summary
Uncontrolled object creation leads to duplicated and hard-to-maintain code.
Creational patterns centralize and abstract object creation to improve flexibility.
They help manage complex creation logic and support changing requirements easily.

Practice

(1/5)
1. Why do creational design patterns manage object creation in software design?
easy
A. To separate the process of creating objects from their usage, improving flexibility
B. To make the code run faster by avoiding object creation
C. To reduce the number of objects created to save memory
D. To enforce strict typing of objects in the system

Solution

  1. Step 1: Understand the purpose of creational patterns

    Creational patterns focus on how objects are created, aiming to separate creation from usage.
  2. Step 2: Identify the benefit of this separation

    This separation allows the system to be more flexible and easier to maintain or extend.
  3. Final Answer:

    To separate the process of creating objects from their usage, improving flexibility -> Option A
  4. Quick Check:

    Object creation separation = Flexibility [OK]
Hint: Creational patterns separate creation from use for flexibility [OK]
Common Mistakes:
  • Thinking creational patterns only improve speed
  • Confusing object creation with memory optimization
  • Assuming creational patterns enforce type rules
2. Which of the following is the correct syntax to implement a simple Factory Method pattern in Python?
easy
A. def Factory(): return Product()
B. class Factory: def create(self): return Product()
C. class Factory: def create(): return Product()
D. class Factory: def create(self): return Product

Solution

  1. Step 1: Check method definition with self parameter

    In Python, instance methods must have 'self' as the first parameter.
  2. Step 2: Verify the method returns an instance, not a class

    The method should return an instance of Product, so 'Product()' is correct, not 'Product'.
  3. Final Answer:

    class Factory: def create(self): return Product() -> Option B
  4. Quick Check:

    Method with self and returns instance = class Factory: def create(self): return Product() [OK]
Hint: Instance methods need 'self' and return object instances [OK]
Common Mistakes:
  • Omitting 'self' in method definition
  • Returning class instead of instance
  • Defining method without parameters
3. Given the following code snippet implementing a Singleton pattern, what will be the output?
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)
medium
A. False
B. Error
C. True
D. None

Solution

  1. Step 1: Understand Singleton __new__ method behavior

    The __new__ method ensures only one instance is created by storing it in _instance.
  2. Step 2: Check if obj1 and obj2 refer to the same instance

    Both obj1 and obj2 call Singleton(), which returns the same _instance object.
  3. Final Answer:

    True -> Option C
  4. Quick Check:

    Singleton returns same instance = True [OK]
Hint: Singleton returns same object, so 'is' comparison is True [OK]
Common Mistakes:
  • Assuming new instance created each call
  • Confusing 'is' with '=='
  • Expecting None or error output
4. Identify the error in the following Builder pattern implementation snippet:
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)
medium
A. print statement syntax is incorrect
B. build_part method does not add parts correctly
C. get_product method returns None instead of product
D. Product class is not defined, causing a NameError

Solution

  1. Step 1: Check for class definitions used

    The code uses 'Product' but does not define it anywhere, leading to NameError.
  2. Step 2: Verify other method correctness

    Methods build_part and get_product are syntactically correct assuming Product exists.
  3. Final Answer:

    Product class is not defined, causing a NameError -> Option D
  4. Quick Check:

    Undefined Product class = NameError [OK]
Hint: Undefined classes cause NameError, check all class definitions [OK]
Common Mistakes:
  • Assuming Product class exists by default
  • Blaming method logic instead of missing class
  • Ignoring error messages
5. In a large system, why is it beneficial to use creational patterns like Abstract Factory instead of directly instantiating objects with new or constructors?
hard
A. It allows the system to create families of related objects without specifying their concrete classes
B. It guarantees the system uses less memory by reusing objects automatically
C. It forces all objects to be created at compile time for faster execution
D. It removes the need for interfaces or abstract classes in the design

Solution

  1. Step 1: Understand Abstract Factory pattern purpose

    This pattern provides an interface to create families of related objects without specifying their concrete classes.
  2. Step 2: Analyze benefits in large systems

    It improves scalability and flexibility by decoupling object creation from usage and allowing easy swapping of object families.
  3. Final Answer:

    It allows the system to create families of related objects without specifying their concrete classes -> Option A
  4. Quick Check:

    Abstract Factory = Create related objects flexibly [OK]
Hint: Abstract Factory creates related objects without concrete classes [OK]
Common Mistakes:
  • Thinking it reduces memory automatically
  • Believing it forces compile-time creation
  • Assuming it removes need for interfaces
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard