Ensure a class has only one instance and provide a global point of access to it.
Sometimes you need to ensure that a class has exactly one instance. For example, a single database connection, a configuration manager, or a logging service shared across the application.
The Singleton pattern ensures that a class has only one instance by:
- Making the constructor private
- Providing a static method that returns the single instance
- Storing the instance as a static variable
Singleton
├── private static instance
├── private constructor
└── public static GetInstance()
- When exactly one instance of a class is needed
- When the single instance should be accessible from a well-known access point
- When the sole instance should be extensible by subclassing
See the Program.cs file for a thread-safe implementation example.
-
Create a .NET console project in this directory:
dotnet new console -n Singleton -f net10.0
-
Replace the generated Program.cs with the provided one
-
Run the application:
dotnet run
- Controlled access to the sole instance
- Reduced namespace pollution
- Permits refinement of operations and representation
- Lazy initialization possible
- Difficult to unit test
- Violates Single Responsibility Principle (manages its own lifecycle)
- Can hide dependencies
- Requires special care in multi-threaded applications