Skip to main content

Singleton Design Pattern with Real-Time Example in C#

The Singleton Pattern ensures that a class has only one instance in the across application and the object instance coordinates across the app.

This pattern is the simplest design pattern and is used to restrict the creation of multiple object instances.

This pattern is the simplest design pattern and is used to restrict the creation of multiple object instances.

A class should have the following structure for the Singleton Design Pattern:

1.      Should have a private or protected constructor. No public and parameterized constructors.

2.      Should have a static property to return an instance of a class.

3.      At least have one non-static public method for a singleton operation.

The Singleton pattern is often used for:

1.      Logging

2.      Database connections

3.      Caching

4.      Thread pools

5.      Data Sharing

The main purpose of the singleton design pattern is to ensure that a class only has one instance and provide a global point of access to it throughout the life of an application.


There are several ways to Implement the Singleton Pattern in C#
1.      Non-thread-safe version
2.      Simple thread safety via locking
3.      Double-checked locking
4.      Safety through initialization
5.      Safe and fully lazy static initialization
6.      Lazy<T>

Let's see the implementation of the Singleton Pattern in C# in depth –

Example 1 for Non-thread-safe version:

//First version - not thread-safe
//Bad code! Do not use it!

public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton() {   }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

Example 2 for Simple thread safety via locking:

//Second version - simple thread-safety

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()  { }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Example 3 for Double-checked locking:

//Third version - attempted thread safety using double-check locking
// Bad code! Do not use it!

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton() {  }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

Example 4 for Safety through initialization:

//Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton() {  }

    private Singleton() {  }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

Example 5- Safe and fully lazy static initialization: 

//Fifth version - fully lazy instantiation

public sealed class Singleton
{
    private Singleton()  {  }

    public static Singleton Instance { get { return Nested.instance; } }       
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }
        internal static readonly Singleton instance = new Singleton();
    }
}

Example 6 –  Lazy<T> :

If you are using .NET 4 (or higher), you should use the System.Lazy<T> type to make the laziness really simple.

//Sixth version - using .NET 4's Lazy<T> type

    public sealed class CountryMaster
    {
        // Static cache to store the list of countries
        private static List<Country> _countyCache;

        // Lazy initialization to ensure the singleton instance is created only when needed
        private static readonly Lazy<CountryMaster> _instnace = new Lazy<CountryMaster>(() => new CountryMaster());

        // Public static property to access the singleton instance
        public static readonly CountryMaster Instance = _instnace.Value;

        // Private constructor to prevent instantiation from outside the class
        private CountryMaster()
        {
            // Initialize the country list when the singleton instance is created
            LoadCountries();
        }

        // Method to load the initial set of countries into the cache
        private void LoadCountries()
        {
            _countyCache = new List<Country>()
            {
                new Country { ID = 0, Name = "India" },
                new Country { ID = 1, Name = "United States" },
                new Country { ID = 2, Name = "UK" },
                new Country { ID = 3, Name = "Mexico" }
            };
        }

        // Method to get the list of countries from the cache
        public List<Country> GetCountries()
        {
            // If the cache is null, reload the initial set of countries
            return _countyCache;
        }

        // Method to refresh the list of countries, simulating a database call
        public List<Country> RefreshCountry()
        {
            // Replace the cache with an updated list of countries
            _countyCache = new List<Country>()
            {
                new Country { ID = 0, Name = "India" },
                new Country { ID = 1, Name = "United States" },
                new Country { ID = 2, Name = "UK" },
                new Country { ID = 3, Name = "Mexico" },
                // Add more countries as needed
            };

            return _countyCache; // Return the refreshed country list
        }
    }

    // Class to demonstrate the usage of the Singleton CountryMaster
    public class Singlton
    {
        public static void Main(string[] args)
        {
            // Get the initial list of countries from the singleton instance
            var listOfCounty = CountryMaster.Instance.GetCountries();
            Console.WriteLine($"GetCountries: ");
            foreach (var country in listOfCounty)
            {
                // Print each country's ID and Name
                Console.WriteLine($"Country ID:  {country.ID}");
                Console.WriteLine($"Country Name:  {country.Name}");
            }

            // Refresh the country list and fetch the updated list
            var refreshListOfCounty = CountryMaster.Instance.RefreshCountry();
            Console.WriteLine($"RefreshCountry: ");
            foreach (var country in refreshListOfCounty)
            {
                // Print each country's ID and Name from the refreshed list
                Console.WriteLine($"Country ID:  {country.ID}");
                Console.WriteLine($"Country Name:  {country.Name}");
            }
        }
    }

    public class Country
    {
        public int ID { get; set; } // Unique identifier for the country
        public string Name { get; set; } // Name of the country
        public string Description { get; set; } // Description of the country
    }


The Singleton pattern, like any design pattern, comes with its own set of advantages and disadvantages. Let's take a look:

Advantages of the Singleton Design Pattern:

Single Instance:  The most obvious advantage is that a Singleton ensures a class has only one instance, and it provides a global point of access to that instance.

 

Global Point of Access: Because the Singleton provides a single, globally accessible point of access to the instance, it's easy to use and avoids the need for passing instances around your code.

 

Lazy Initialization: The instance is created only when it's requested for the first time, which can be beneficial for performance. This is particularly true if the creation of the instance is resource-intensive.

 

Memory Efficiency: It helps in saving memory by having only one instance for the entire application, especially in scenarios where the object is large or consumes significant resources.

 

Disadvantages of the Singleton Design Pattern:

Global State: Because the Singleton pattern provides a global point of access, it introduces a global state to your application. This can make it harder to reason about the flow of data and can lead to unintended dependencies between classes.

 

Testing Difficulties: Singletons can be difficult to test because they introduce a global state. When testing a class that depends on a Singleton, it's challenging to isolate and control the environment.

 

Inflexibility: The singleton pattern creates a rigid structure in the application. If you later decide that you need multiple instances or want to change the instantiation logic, you might find it challenging to modify the Singleton implementation.

 

Thread Safety: The basic Singleton implementation is not thread-safe. If multiple threads try to access the instance simultaneously and it hasn't been created yet, it might result in the creation of multiple instances. Adding thread safety can make the code more complex.

 

Violates Single Responsibility Principle:

Sometimes, a Singleton class might take on responsibilities beyond managing its instance, violating the Single Responsibility Principle. For example, it might handle configuration settings, logging, and other concerns in addition to being a singleton.


When to Use:

When a Single Instance is Necessary:

Use a Singleton when you need to ensure that a class has exactly one instance and when that instance must be accessible from a global point of entry.

 

When Lazy Initialization is Preferred:

If the creation of the instance is resource-intensive and you want to defer it until it's actually needed, a Singleton can be a good choice.

 

When Global State is Acceptable:

If having a global state is acceptable for your application and doesn't introduce issues, a Singleton might be suitable.


In conclusion, the Singleton pattern can be a powerful tool, but it should be used judiciously. It's essential to weigh its advantages against its disadvantages and consider alternatives, especially in the context of modern software design principles and patterns.



By Anil Singh | Rating of this article (*****)

Popular posts from this blog

nullinjectorerror no provider for httpclient angular 17

In Angular 17 where the standalone true option is set by default, the app.config.ts file is generated in src/app/ and provideHttpClient(). We can be added to the list of providers in app.config.ts Step 1:   To provide HttpClient in a standalone app we could do this in the app.config.ts file, app.config.ts: import { ApplicationConfig } from '@angular/core'; import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; import { provideClientHydration } from '@angular/platform-browser'; //This (provideHttpClient) will help us to resolve the issue  import {provideHttpClient} from '@angular/common/http'; export const appConfig: ApplicationConfig = {   providers: [ provideRouter(routes),  provideClientHydration(), provideHttpClient ()      ] }; The appConfig const is used in the main.ts file, see the code, main.ts : import { bootstrapApplication } from '@angular/platform-browser'; import { appConfig } from ...

Top 15+ Angular 17 Interview Questions Answers | For Experienced Professionals as well

G Google team released the latest version of Angular – Angular 17 on November 6, 2023, creating a significant milestone for the super fast front-end development. What Are the New Features in Angular 17? 1.       Angular 17 is the highly anticipated release for the community, bringing many new exciting features, updates, and improvements. 2.       New Syntax for Control Flow in Templates - new @if, @switch, @for, @case, @empty @end control flow syntax 3.       Deferred Loading - @defer partial template 4.       The Angular signals API 5.       Angular SSR and client hydration 6.       Automatic Migration to Build-in Control Flow 7.       Build Performance with ESBuild 8.       By default, set this newly generated component as a standalone, and now we don't have an app module file. To use (ng...

SOLID-Liskov Substitution Principle (LSP) Real-Time Example in C#

The SOLID Principles are the design principles that enable us to manage several software design problems. These principles provide us with ways to move from tightly coupled code to loosely coupled and encapsulated real business needs properly. Also readable, adaptable, and scalable code. The SOLID Principles  guide developers as they write readable, adaptable, and scalable code or design an application. The SOLID Principles can be applied to any OOP program. The SOLID Principles were developed by computer science instructor and author Robert C. Martin. Now, SOLID principles have also been adopted in both agile development and adaptive software development. The 5 principles of SOLID are: 1.       Single Responsibility Principle (SRP) 2.       Open-Closed Principle (OCP) 3.       Liskov Substitution Principle (LSP) 4.       Interface Segregation Principle (ISP) 5. ...

39 Best Object Oriented JavaScript Interview Questions and Answers

Most Popular 37 Key Questions for JavaScript Interviews. What is Object in JavaScript? What is the Prototype object in JavaScript and how it is used? What is "this"? What is its value? Explain why "self" is needed instead of "this". What is a Closure and why are they so useful to us? Explain how to write class methods vs. instance methods. Can you explain the difference between == and ===? Can you explain the difference between call and apply? Explain why Asynchronous code is important in JavaScript? Can you please tell me a story about JavaScript performance problems? Tell me your JavaScript Naming Convention? How do you define a class and its constructor? What is Hoisted in JavaScript? What is function overloadin...

List of Countries, Nationalities and their Code In Excel File

Download JSON file for this List - Click on JSON file    Countries List, Nationalities and Code Excel ID Country Country Code Nationality Person 1 UNITED KINGDOM GB British a Briton 2 ARGENTINA AR Argentinian an Argentinian 3 AUSTRALIA AU Australian an Australian 4 BAHAMAS BS Bahamian a Bahamian 5 BELGIUM BE Belgian a Belgian 6 BRAZIL BR Brazilian a Brazilian 7 CANADA CA Canadian a Canadian 8 CHINA CN Chinese a Chinese 9 COLOMBIA CO Colombian a Colombian 10 CUBA CU Cuban a Cuban 11 DOMINICAN REPUBLIC DO Dominican a Dominican 12 ECUADOR EC Ecuadorean an Ecuadorean 13 EL SALVA...