The Singleton – Design Pattern

The Singleton – Design Pattern

The Singleton Design Pattern ensures that only a single instance of a given object can exist.

It does this by making the class constructor private so that it will be the singleton itself, and singleton class has full control over when the class instance is created.  In order to gain access to an instance of a class that implements the Singleton pattern, the developer must call a shared/static method of that Singleton class.

An example of Singleton Pattern implementation in C#

public class MySingletonSample

{

    //shared members

    private static MySingletonSample _instance = new MySingletonSample();

    public static MySingletonSample Instance()

    {

        return _instance;

    }

    //instance members

    private MySingletonSample()  //over riding contruction to avoid instantiation

    {

        //public instantiation disallowed

    }

    //other instance members

    //…

}
With the Singleton Design Pattern in place, a developer can easily access that single object instance without needing to worry about  problem of  creating multiple instances.

This pattern is really useful when we want to share a single instance of an object all across the application.

For example some common data and commonly used helper methods that you want to shared across the whole Application, you can choose this Singleton pattern, depending on your need.

2 thoughts on “The Singleton – Design Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.