The Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance. It is commonly used for logging, caching, thread pools, database connections, and other scenarios where you want to restrict the instantiation of a class to a single object. Here’s a C# example of the Singleton pattern along with a use case for a logger:
Singleton Implementation:
public class Logger
{
private static Logger instance;
private string logFile = "log.txt";
// Private constructor to prevent instantiation from other classes.
private Logger() { }
// Method to access the single instance of the Logger.
public static Logger GetInstance()
{
if (instance == null)
{
instance = new Logger();
}
return instance;
}
public void Log(string message)
{
// Log the message to the file.
File.AppendAllText(logFile, $"{DateTime.Now}: {message}\n");
}
}
Use Case – Logging:
In this example, we’ll use the Singleton pattern to create a logging system. The Logger class ensures that only one instance is created, and all log messages are written to the same log file.
class Program
{
static void Main(string[] args)
{
// Get the Logger instance
Logger logger = Logger.GetInstance();
// Log some messages
logger.Log("Application started.");
logger.Log("User logged in.");
logger.Log("Error: Invalid input.");
// Get the same instance elsewhere in your code
Logger anotherLogger = Logger.GetInstance();
anotherLogger.Log("Another log message.");
// Both logger and anotherLogger refer to the same Logger instance.
}
}
In this example, the Singleton pattern ensures that only one instance of the Logger class is created throughout the application’s lifecycle. All log messages are written to the same log file, and you can access the Logger instance from different parts of your code.
The Singleton pattern provides a convenient way to manage shared resources or state within an application, ensuring that there’s a single point of access to that resource or state.