Saturday 9 January 2016

Singelton Design Pattern

Singleton pattern creates a class which can have a single object throughout the application, so that whenever any other object tries to access the object of the class, it will access the same object always.

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent


  1. Ensure that only one instance of a class is created.
  2. Provide a global point of access to the object.


Code :

/// <summary>
/// Implementation of Singleton Pattern
/// </summary>
public sealed class SingleTon
{
    private static SingleTon _instance = null;
    private SingleTon() // Made default constructor as private
    {
    }
    /// <summary>
    /// Single Instance
    /// </summary>
    public static SingleTon Instance
    {
        get
        {
            _instance = _instance ?? new SingleTon();
            return _instance;
        }
    }

    # region Rest of Implementation Logic

    //Add As many method as u want here as instance member. No need to make them static.

    # endregion
}

class test
{
    static void Main()
    {
        var instObj = SingleTon.Instance;
    }
}

No comments:

Post a Comment

Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft