Saturday, November 21, 2009

Singleton pattern

  • Class will have only one instance
  • And there will be a global point to access it


Reference: 


http://www.dofactory.com/Patterns/PatternSingleton.aspx

How to implement singleton?
  1. Create private constructor for CLASS
  2. Declare a static member of the CLASS
  3. Declare a static property , in which new object of CLASS creates if it does not exist.
Sample:

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

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

class TestSingleton
{
    private TestSingleton()
    {
    }

    public static void DoTest()
    {
        ////Singeleton
        Singleton obj1 = Singleton.Instance;
        Singleton obj2 = Singleton.Instance;

        // Test for same instance
        if (obj1 == obj2)
            System.Console.WriteLine("both instances are same!");
    }
}

No comments: