I have a rather large c++ application with some "managers" like a hook manager, an event manager, how could I expose those systems without falling in the singleton hell ?
Assistant
Exposing and managing global systems like managers in a large C++ application can be a design challenge. The "singleton hell" you referred to often happens when singletons are overused, negatively affecting testability, maintainability, and introducing hidden dependencies. Here are strategies to manage your systems without falling into these pitfalls:
Inversion of Control and Dependency Injection:
Instead of using singleton patterns, consider using dependency injection (DI). Pass the required managers to the classes that need them via constructor parameters or setter methods.
Use a DI container or framework to manage the lifecycle and dependencies of your objects. This approach makes your code more modular and easier to test.
Service Locator Pattern:
Implement a service locator pattern where a central registry exposes different managers or services. Consumers can request a specific service from the locator.
Though more flexible than singletons, be cautious as overuse can still obscure dependencies.
Modular Design:
Break down your application into smaller, feature-oriented modules. Each module can manage its own dependencies and managers.
Use interfaces to abstract the functionality of different managers, making it easier to swap implementations or mock them during testing.
Observer or Event-Based Architecture:
If your managers deal primarily with notifications or state changes, consider using an event-based system or observer pattern to decouple components.
This approach reduces direct dependencies between classes, allowing managers to notify interested components about changes.
Factory Pattern:
Use factory patterns to create instances of your managers or other key components. This method allows control over instance creation and can help with managing lifecycle and configurations.
Configuring Managers at Startup:
During application startup, configure and initialize all managers in a centralized setup routine. Pass these managers wherever needed explicitly.
Consider using scopes or context objects to conveniently pass several related managers as a single object.
Smart Pointers for Lifecycle Management:
Use smart pointers (like std::unique_ptr or std::shared_ptr) for manager instances to enforce proper resource management and ownership semantics.
Interface Segregation:
Implement interfaces or abstract classes for your managers that define specific behaviors. Classes can then depend on abstractions rather than concrete implementations, increasing flexibility.
By implementing these strategies, you can manage your systems effectively while avoiding the downsides associated with singletons. The goal is to make your design more modular, testable, and maintainable, with clear and explicit dependencies.