Blog / Design Patterns
The Singleton Design Pattern in C# and .Net
  • Dec 11, 2020
  • 91
  • 75

The last design pattern that I want to mention in Creational Category is the Singleton Design Pattern. So, let’s see what is it and how we can implement this pattern in our program.

Note: Code can be downloaded at my Github


Advertisement
 


1. What is the Singleton Design Pattern?

As the name suggests, Singleton pattern is a way to control the number of instance of a class to be only one. By doing so, the application is able to provide a global access point to that single instance.

The Singleton Design Pattern 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.


2. When to implement the Singleton Design Pattern?

The motivation to use Singleton is when your applications have some components which only make sense to have one instance in the system such as a Database Repository or an Factory Object.

The components above are examples of instances that should be created one only and everyone can access to the same instance.

The Singleton Design Pattern helps to prevent anyone creating additional copies of the instance, take care of the lazy instantiation and thread safety.

3. How to Implement Singleton Design Pattern?

We can implement Singleton Design Pattern for the Database class as we mentioned in above example here. 

Step 1: Create classes for Entities

To simplify, we take a User class as an example.

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
 
    public override string ToString()
    {
        return $"Name: {Name}, Age: {Age}";
    }
}

Step 2: Create the Singleton interface and class

We are implement Singleton for Database, therefore, we create an interface IDatabase and a class SingletonDatabase:

public interface IDatabase
{
    User GetUserByName(string name);
}
 
public class SingletonDatabase : IDatabase
{
    private string database;
 
    private SingletonDatabase()
    {
        Console.Write("Initializing database");
        Console.WriteLine();
 
        database = "[ { \"Name\": \"Lucas\", \"Age\": 29 }, { \"Name\": \"Eric\", \"Age\": 28 } ]";
    }
 
    private static SingletonDatabase instance = new SingletonDatabase();
 
    public static SingletonDatabase Instance = instance;
 
    public User GetUserByName(string name)
    {
        List users = JsonConvert.DeserializeObject<>>(database);
        return users.Where(u => u.Name == name).FirstOrDefault();
    }
}

Notice that the constructor for SingletonDatabase class is private and there is a public member called Instance to represent the single instance of this Database.

There is a function called GetUserByUserName which get user data by filtering the JSON string database. Note that the JSON string database represents the database in this example and it is initiated only once in the private constructor.

On the client side, we can run below code to get user by using GetUserByUserName function:

class Program
{
    static void Main(string[] args)
    {
        var db = SingletonDatabase.Intance;
        var user = db.GetUserByName("Lucas");
        Console.WriteLine(user.ToString());
 
        var db2 = SingletonDatabase.Intance;
        var user2 = db2.GetUserByName("Eric");
        Console.WriteLine(user2.ToString());
    }
}

In the above code, even when we create a second database object called db2, it is referred to the only database instance that we created before. The "Initializing database" message is printed once only.

Done! This is how the Singleton Prototype is implemented basically. The actual implementation in real world applications maybe more complicated but I hope you get the idea of how to implement Singleton in your project.



If you have a Website or a Web API developed by using .Net Core and looking for a way to publish your applications, this post will explain how to do it using GoDaddy Windows Hosting.Note: at this mome ...

Search text in Stored Procedure in SQL SELECT DISTINCT o.name AS Object_Name, o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id = o ...

Using cherry-pick to select specific commits for your Pull Request.1. Create a new branch based on the target of the Pull Requestgit branch cherry-branch origin/master2. Switch to a new branchgit chec ...

After deployment Angular and API on IIS, it's working fine unless I refresh the page. Once refreshed, the web encountered 404 error. In this article, I will explain how to resolve this.Since Angular i ...

There are some benefits of keeping both UI and API parts in the same place for small projects. In this article, I will explain how I did to deploy Angular Web and ASP .Net Core API in the same folder ...

I got CORS error after publishing my API and Angular app to IIS even though CORS is enabled and the origins of the Angular app is added. Below is how I resolved this issue.Just simple, make sure you s ...

1. The Situation:Error Message:&nbsp;Pulse Secure Application failed to load Java. Please install correct JRE version.Description: This issue happens when I'm using a M1 Mac with a correct version of ...

Accelerated Mobile Pages (AMP)&nbsp;focuses on delivering static content from publishers as quickly as possible and possibly rewards early adopters with a boost in rank. Let's see how to implement it ...

Below is how to decrypt/convert a Hex string value into text using VB.Net:Decrypting Hex string value to string in VB.Net Function HexToString(ByVal hex As String) As String Dim text As New Sy ...