Wednesday 15 October 2014

Implement Singleton Pattern

How to implement Singleton Pattern :

Suppose I have a class A which has all the functionality and I want to make that class visible to all  the users but only a single instance should be created across all the users. Then I would use singleton pattern to implement such scenario :

public class A
    {
        //added for implementing Singleton Pattern
        private A() { }
       
        private staticA MyObject;
        public static A Createinstance()
        {
            if (MyObject == null)
            {
                MyObject = new A();
            }
            return MyObject;
        }

//Your own business logics and methods....
}

Now My class has been implemented. We will now implement this class and create the object of the same in my main class or whereever I want to use this class in my application.

Class MyMainClass
{
         A MyInstance  = A.Createinstance();
}

Now you can call the methods of the class using the object MyInstance. Wherever it be called and whatever number of times the object of the A class be created the instance will only be created once.

Thanks :)

No comments:

Post a Comment