skip to content
Mohammad Rebati

Understanding the Singleton Design Pattern

/ 2 min read

Introduction to the Singleton Design Pattern

The Singleton Design Pattern is a creational design pattern that ensures a class has only one instance while providing a global point of access to that instance. It involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

Key Concepts

  • Single Instance: Ensures that only one instance of the Singleton class ever exists.
  • Global Access: Provides global access to that instance.

Benefits

  • Controlled Access: There is exactly one instance of a class that is accessible from anywhere in the application.
  • Lazy Initialization: Often, the Singleton is only created when it is first needed.
  • Reduced Global State: Helps in reducing global state usage in an application.

Example in Code

Here’s how you might implement the Singleton Pattern in C# to ensure that there is only one instance of a database connection manager:

public class DatabaseManager
{
private static DatabaseManager _instance;
private static readonly object _lock = new object();
// Constructor is 'protected' to prevent instantiation outside the class
protected DatabaseManager()
{
}
public static DatabaseManager Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
_instance = new DatabaseManager();
}
}
}
return _instance;
}
}
public void Query(string sql)
{
Console.WriteLine("Executing query: " + sql);
}
}
// Example usage
class Program
{
static void Main(string[] args)
{
DatabaseManager manager = DatabaseManager.Instance;
manager.Query("SELECT * FROM users");
}
}