top of page
Writer's pictureNimesh Patel

SINGLETON DESIGN PATTERN

Shared Objects? Singleton, please!



Singleton design patterns are a set of rules of class that only lets one instance of a class exist during the lifetime of the application. A singleton satisfies 3 requirements:

  1. controls concurrent access to a shared resource.

  2. access to the resource will be requested from multiple, disparate parts of the system.

  3. there can be only one object.

“Singletons are used when a resource needs to be used by more than one client, and the resource's date needs to be persisted. Use singleton sparingly”

We can create the Singleton class when we need it (lazy loading instantiation) or on the startup of the application. Once loaded the class will never be deleted. I don't use singletons very often because if we have a lot of these, memory will be filled up fast. You should be very selective when using a singleton pattern. Do we really need this data open all the time? On the other end, there are times when you need to share data to access the applications, and it makes sense to keep it in memory then load it continually. An example of when I have used singleton is configuration data. It didn't make sense to load it in every time I needed it, so I kept it in memory.


Real-world scenarios when singleton can be used

  • Logging class.

  • Configuration classes

  • Connections to databases

Example


We want to share a singleton of country capitals. We do not want these to change, and we want to share one instance between clients. We want the clients to be able to add countries, capitals as needed, and other clients should be able to read them.


Create a private constructor


private CountriesCapitals()
{
        capitals.Add("Australia", "Canberra");
        capitals.Add("Belgium", "Brussels");
        capitals.Add("Netherlands", "Amsterdam");
        capitals.Add("China", "Beijing");
        capitals.Add("Russia", "Moscow");
        capitals.Add("India", "New Delhi");
}

  • Private so external clients cannot call the constructor directly.

Static field to store the instance of the class

private static readonly CountriesCapitals _instance = new CountriesCapitals();

  • ReadOnly is important, that means we cannot overwrite this variable with something else/ (once it is assigned it cannot be reassigned with a new value)

  • Static, you can access the instance of TableServers without needing the class to be instantiated

  • Private- so it cannot be called by external classes

Get method that returns the instance of the class

Public Static CountriesCapitals GetCountriesCapitals ()
{
    return _instance;
}

Public - so can be called by external classes

Static - so can be called by a client, e.g"TableServers.GetTableServers"



Full Singleton Class

public class CountriesCapitals
    {
        private static readonly CountriesCapitals _instance = new CountriesCapitals();

        private Dictionary<string, string> capitals =  new Dictionary<string, string>();

        private CountriesCapitals()
        {
            capitals.Add("Australia", "Canberra");
            capitals.Add("Belgium", "Brussels");
            capitals.Add("Netherlands", "Amsterdam");
            capitals.Add("China", "Beijing");
            capitals.Add("Russia", "Moscow");
            capitals.Add("India", "New Delhi");
        }

        public static CountriesCapitals GetCountriesCapitals()
        {
            return _instance;
        }

        public void AddCountryCapital(string country, string capital)
        {
            capitals.Add(country, capital);
        }
    }








28 views0 comments

Recent Posts

See All

Comentários


bottom of page