Creational Pattern
Creational patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. They abstract the instantiation process, making a system independent of how its objects are created.
Singleton Pattern
- The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.
- Use Cases:
- Database Connections: Managing a single database connection pool.
- Configuration Management: Ensuring a single configuration instance is used throughout the application.
Basic Singleton in Python
Singleton with Thread Safety For multi-threaded applications, ensure thread safety to prevent multiple instances.
Practical Example in FastAPI: Database Connection Management
Factory Pattern
The Factory pattern defines an interface for creating objects but allows subclasses to alter the type of objects that will be created. It promotes loose coupling by eliminating the need to bind application-specific classes into the code.
Use Cases in FastAPI
- Creating Service Classes: Depending on the context, instantiate different service implementations.
- Database Model Factories: Dynamically creating different database models based on configuration.
- API Response Factories: Generating responses based on various conditions or formats.
Advantages
- Encapsulates object creation.
- Promotes code reusability and flexibility.
- Facilitates easy addition of new types without modifying existing code.
Disadvantages
- Can introduce complexity if overused.
- Might obscure the code flow, making it harder to trace object creations.
Factory Pattern with FastAPI: Service Creation
Builder Pattern
The Builder pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
Use Cases in FastAPI
- Complex Object Construction: Building objects with numerous optional parameters.
- Request/Response Builders: Dynamically assembling responses based on various conditions.
- Query Builders: Creating complex database queries programmatically.
Advantages
- Provides precise control over the construction process.
- Simplifies the creation of complex objects.
- Enhances code readability and maintainability.
Disadvantages
- Can introduce additional classes and complexity.
- Might be overkill for simple object creation scenarios.
Builder Pattern with FastAPI: Request Filtering Imagine an API that allows users to filter items based on various optional parameters.
Was this page helpful?