Motivation: When you need a unique object
Be Careful: In case of accessing it in multiple threads
- The singleton pattern ensures the uniqueness of an object.
- You implemented the pattern correctly if only one instance of the given type can be created and that instance cannot be cloned.
- The singleton instance must be thread-safe since many different components might access it concurrently.
- You must implement protection against concurrent use for the initialization phase of the singleton and any access to its public properties or methods.
The singleton pattern ensures only one instance of a given type exists, and that instance cannot be copied or cloned. The singleton must be thread-safe since the shared instance can be concurrently accessed by several threads.
The aim is to create a class which can have exactly one instance. But it also requires attention when implementing it. We must prohibit the copying or cloning of the singleton instance. We can only use reference types, that is classes since value types are copied upon assigning them to a new variable. The singleton instance represents a shared resource that can be used by all components that depend on the given type. These components may access the singleton instance concurrently from different threads. Therefore, the singleton class must be thread-safe. We must protect against concurrent access, its instantiation, and any access to its public members and methods.
Examples of Singleton:
- File manager
- Logger system
- Analytics system