Singleton
When to use the Singleton Pattern?
Use the Singleton pattern when exactly one object is needed to coordinate others across a system.
Below is an example of a singleton pattern:
Explanation:
This example creates a Logger
class that allows you to log messages with different log levels (e.g., 'debug', 'info', 'error'). The LoggerFactory
object ensures that only one Logger
instance exists throughout your application.
Here's why this is useful:
Centralized Logging: You have a single point of access for logging in your application.
Consistent Log Level: The log level is set once when the first instance is created, ensuring consistency in how messages are logged.
Access to Log History: The
getLogs()
method lets you retrieve the logged messages, which can be helpful for debugging or auditing.
"This pattern is beneficial in situations where you want to control how logging happens across your application and maintain a single log history.
Identifying Singletons can be difficult. If youβre importing a large module, you will be unable to recognize that a particular class is a Singleton. As a result, you may accidentally use it as a regular class to instantiate multiple objects and incorrectly update it instead.
Challenging to test. Singletons can be more difficult to test due to issues ranging from hidden dependencies, difficulty creating multiple instances, difficulty in stubbing dependencies, and so on.
Need for careful orchestration. An everyday use case for Singletons would be to store data that will be required across the global scope, such as user credentials or cookie data that can be set once and consumed by multiple components. Implementing the correct execution order becomes essential so that data is always consumed after it becomes available and not the other way around. This may become challenging as the application grows in size and complexity."
Last updated