When to Use Singleton Design Pattern
- There must be one and only one instance of a class;
- The class must be accessible to clients;
- The class should not require parameter as part of its construction;
- and when creating the instance that is expensive, a Singleton can improve performance.
- Accessing to a File System (Logger, Database);
- Accessing to a Shared Resources
- Log-in Credentials
Problems | Description |
---|---|
Anti-pattern | It violates the Single Responsibility Principle. It introduces global state that spans all over the application. |
Not thread safe | The basic implementation of Singleton is not thread safe. Especially in web application. Locking the resource/singleton before instantiating would solve the problem. |
Difficult to test | Test doubles cannot be implemented. To test it, you need to test the actual class. |
The UML Class Diagram
Class/Interface | Description |
---|---|
Singleton | A private class which is responsible for creating and maintaining its own unique instance. |
Example
The sample code presented here is a File Logger sample that supports thread safe. A test to insure that only one instance will be created is also provided in this code.
The Project Structure
The Singleton File Logger UML Class Diagram
File Logger Mapping on Singleton Design Pattern
Singleton Design Pattern | Singleton File Logger |
---|---|
Singleton | FileLogger |
The Codes
Program.cs
The Output
If we look closely on the output, the FileLogger was invoke twice but it is only initialized once. Meaning there is only one instance despite assigning to different variables.
Ok. Thank you! Hope this is helpful.