Quantcast
Channel: Geekswithblogs.net | design pattern Posts
Viewing all articles
Browse latest Browse all 50

Singleton Design Pattern

$
0
0

Design Patterns sounds like an Italian recipies. If you you tell your grand mother that you cooked Bolognese and Pasta for evening, she wouldn't ask you how, as the recipie is famous enough to make scence to everyone. She wouldn't expect a creamy pasta with chicken unless you decided to make her surprise. 

Same story when you coding. In fact the benefit of using Design Patterns is that when you say, for example, you have implemented Singleton, your work mate would have a picture of the code on spot and its make everyone's life much more easier.

One of the simplest one to start is Singleton. The usage is when you want to have a single instance of a class in the entire solution:

 

    publicclassSingleton

    {

        privatestaticSingleton instance;//Static variable to hold single instance

        //Other variables...

   

        //Private Constructor. So only Singleton can instantiate itself

        private Singleton() { }

 

        //Lazy instantiation (Never get created if doesn't needed)

        publicstaticSingleton Instance

        {

            get

            {

                if (instance == null)

                {

                    instance = newSingleton();

                }

                return instance;

            }

        }

        //Other Methods...

    }


Viewing all articles
Browse latest Browse all 50

Trending Articles