Skip to content

Singleton Design Pattern (Creational)

Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.

The Singleton pattern solves two problems at the same time, violating the Single Responsibility Principle:

  1. Ensure that a class has just a single instance. Why would anyone want to control how many instances a class has? The most common reason for this is to control access to some shared resourceβ€”for example, a database or a file.
  2. Provide a global access point to that instance. Remember those global variables that you used to store some essential objects? While they’re very handy, they’re also very unsafe since any code can potentially overwrite the contents of those variables and crash the app.

All implementations of the Singleton have these two steps in common:

  • Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.
  • Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.

If your code has access to the Singleton class, then it’s able to call the Singleton’s static method. So whenever that method is called, the same object is always returned.

The Government is an excellent example of the Singleton pattern. A country can have only one official government. Regardless of the personal identities of the individuals who form a government, the title, β€œThe Government of X,” is a global point of access that identifies the group of people in charge.

classDiagram
    class Singleton {
        - instance: Singleton
        - Singleton()
        + getInstance() Singleton
    }
class Database:
# The field for storing the singleton instance should be
# declared static.
private static field instance: Database
# The singleton's constructor should always be private to
# prevent direct construction calls with the `new` operator.
private constructor Database():
# Some initialization code, such as the actual
# connection to a database server.
# ...
# The static method that controls access to the singleton
# instance.
public static method getInstance():
if (Database.instance == null):
acquireThreadLock(): # Ensure that the instance hasn't been created yet by another thread.
if (Database.instance == null):
Database.instance = new Database()
return Database.instance
# Finally, any singleton should define some business logic
# which can be executed on its instance.
public method query(sql):
# For instance, all queries of an app go through this
# connection.
# ...
  • Use the Singleton pattern when a class in your program should have just a single instance available to all clients; for example, a single database object shared by different parts of the program.
  • Use the Singleton pattern when you need stricter control over global variables.
  1. Add a private static field to the class for storing the singleton instance.
  2. Declare a public static creation method for getting the singleton instance.
  3. Implement β€œlazy initialization” inside the static method. It should create a new object on its first call and put it into the static field. The method should always return that instance on all subsequent calls.
  4. Make the constructor of the class private. The static method of the class will still be able to call the constructor, but not the other objects.
  5. Go over the client code and replace direct calls to the singleton’s constructor with calls to its static creation method.

Pros:

  • You can be sure that a class has only a single instance.
  • You gain a global access point to that instance.
  • The singleton object is initialized only when it’s requested for the first time.

Cons:

  • Violates the Single Responsibility Principle. The pattern solves two problems at the time.
  • The Singleton pattern can mask bad design, for instance, when the components of the program know too much about each other.
  • The pattern requires special treatment in a multithreaded environment so that multiple threads won’t create a singleton object several times.
  • A Facade class can often be transformed into a Singleton since a single facade object is sufficient in most cases.
  • Abstract Factory, Builder, and Prototype can all be implemented as Singletons.

public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance => _instance;
private Singleton()
{
// Private construtor
}
public void DoSomething()
{
Console.WriteLine("Doing something...");
}
}
// Usage
class Program
{
static void Main()
{
var s1 = Singleton.Instance;
var s2 = Singleton.Instance;
Console.WriteLine(s1 == s2); // True
}
}