The Singleton design pattern is one of the creational pattern from ‘Gang of Four’ (GoF), and it ensures that a class only has one instance, and provide a global point of access to it. The Singleton pattern restricts a class to instantiate its multiple objects. The Singleton defines an Instance operation that lets clients access its unique instance, and also is responsible for creating and maintaining its own unique instance.

How Singleton works

This is the UML class diagram:

This class has a property that generally is private, and has a method that returns the instance of the object. In the “Instance” method, it’s checked if the instance of the class was already created, and if it was it will return the created instance, otherwise, it will create an instance, and next time that this class is called it will return the same created instance. This can be a static class or use a static method.

When Singleton can be used

If you have a functionality that just handle something or just process something, and does not need to know the state of the object (is totally static), it’s not necessary to have many instances of the same object, spending memory to do something that a single instance can do. For some components, it only makes sense to have one instance in the system, for example:

  • Database repository — If you have an object which accesses the database, and it loads up the database in the constructor into memory and then gives out information about the content of the database once it’s loaded. So once you read the database you do not need to read it again (especially when you are testing the code).

So Singleton can be used in situations where the constructor call to a particular object is particularly expensive and you only need to have this call being called once (needs one, and only one instance of an object), and once that you construct the singleton object, you will provide everyone with the same instance of that object that was instantiated, avoiding that other clients make new copies of that object.

Structural code in C#

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

To implement and execute the examples for this article, I’ve created a console application using .NET Core. For this structural example, we have two files, the Singleton and the Program class. This is the Singleton class:

The “_instance” property is a private property and it is a property of the same class. This property is static, so when it is created it will be kept. The Singleton class constructor is protected, so the way to create an object of type Singleton is through the Instance method. What will happen is that always when the Instance method is called, it will check if an instance of Singleton class already exists, and if exists, it will return the instance, otherwise it will create a new instance, this way it will only exist one single instance of the Singleton class.

This is the main class in the Program class where we make the call to the Singleton class:

Because these two objects are the same instance of the Singleton class, the result is that this text will be displayed:

Objects are the same instance

Singleton in a real-world scenario

The Singleton pattern simply uses a private constructor and a static readonly instance variable that is lazily initialized. Thread safety is guaranteed by the compiler.

On the previous example we saw the structure of the pattern, now let’s see how we can apply this pattern into a real-world scenario. On this example, there are four classes: Singleton, LoadBalancer, Server, and the Program class. The Server class is a simple class with three properties:

This is the Program class which will make a call to the Singleton class:

The LoadBalancer class is where we create the Servers and where we have the methods to get the servers:

When the LoadBalancer is called, it will create a new instance of the class, and after that, always when the GetLoadBalancer method is called, it will always return the same instance that was created before.

This is the Singleton class where we have the method to execute the operation:

On this class, there are four variables that have a call to the method GetLoadBalancer from the LoadBalancer class, which will return an instance of the LoadBalancer class. This instance is returned in a Singleton format, so when this be executed, it will be printed that they are the same instance.

Always when the method “GetLoadBalancer” is called, because it is a private method, only one instance will be created, so for example, the second time or the next times that this method is called, it will not create a new instance, but it will use the same instance that was already created before.

On the lopping, there is a call to get the next server from LoadBalancer class, and will be displayed the name of the server. The order that the server will be displayed it will be random each time the operation is executed, because we are using “Random”, but you can debug the application and see that the Ids will be always the same five ids for each server. This is the result:

Same instanceDispatch request to: ServerI
Dispatch request to: ServerI
Dispatch request to: ServerII
Dispatch request to: ServerI
Dispatch request to: ServerII
Dispatch request to: ServerIV
Dispatch request to: ServerIII
Dispatch request to: ServerIII
Dispatch request to: ServerI
Dispatch request to: ServerV
Dispatch request to: ServerI
Dispatch request to: ServerI
Dispatch request to: ServerI
Dispatch request to: ServerIII
Dispatch request to: ServerV

In .NET Core, it’s also possible to use Dependency Injection to inject the class in a Singleton way, instead of implementing the Singleton pattern, this way you will also have the same benefit which is having the same memory allocation.

This is the link for the code:

https://github.com/henriquesd/DesignPatterns

Thanks for reading!

.NET Full-Stack Developer | C# | .NET | .NET CORE | ASP.NET MVC | Unit Test | Angular