Singleton - Creational Design Pattern

Introduction

There are times, when one need to have a class which can be only instantiated once. Singleton Design Pattern addresses to such situation by providing a design for such classes (known as Singleton class).

Description:
There are at least two solutions or scenario for implementing Singleton Class. The first solution says that there should be only one shared object and reference to that object should be available only through static method like GetInstance() while making the constructor private. A number of clients can be awarded the reference to such shared object. The second solution says that the constructor should be public (as it appears in most cases) but once an object has been instantiated, an exception should be thrown for each successive constructor call; thus limiting the class to only one object.

An Example:

First case Singleton can be used in a data repository or data collection where creation of more than one object can be resource wastage. Hence each client is given a reference to a single shared object to operate on. While the second case Singleton can be used in locking mechanisms. Once a client has got the object, no other client can have an object.

Class Diagram:

ClassDiagram1

Implementation:

Let us first discuss the code of first case Singleton which is like:

 class Singleton
    {
        private static Singleton instance;
        private static int numOfReference;
        private string code;
        private Singleton()
        {
            numOfReference = 0;
            code = "Deepak Kamboj";
        }
        public static Singleton GetInstance()
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            numOfReference++;
            return instance;
        }
        public static int Reference
        {
            get { return numOfReference; }
        }
        public string Code
        {
            get { return code; }
            set { code = value; }
        }
    }

There are 3 fields in the Singleton class. Static field instance is a reference to shared object in this Singleton class. Static field numOfReference is an integer variable to hold the number of current references to the single shared object of Singleton class. Code is a string value, it is used to demonstrate that the object is shared b/w references and change made to this field through one reference can be realized through other reference.

The constructor is made private and used to initialize the numOfReference and default value of code. GetInstance() method checks the instance, if it is null then it assign it an instance of Singleton otherwise return the old reference. GetInstance() also increments the numOfReference each time it is called to keep track of current number of reference to our shared instance. Property Reference returns the number of reference referencing our shared object while Code property can be used to set/get the code string of shared object.

The second case Singleton class (Singleton2) looks like:

 public class Singleton2
    {
        private static int numOfInstance = 0;
        public Singleton2()
        {
            if (numOfInstance == 0)
            {
                Console.WriteLine("\r\nCreating First " 
                                + "Object of Singleton2 class...");
                numOfInstance++;
            }
            else
            {
                throw new Exception("This class is Singleton" +
                    ", so only one object of it can be instantiated.");
            }
        }
    }

Here we make the constructor public and use a private field numOfInstance which is incremented for each constructor call. If numOfInstance is zero (no object is yet instantiated), a new object is allowed to made. But, if this value is not zero (there is already an object of Singleton2 class, an exception is thrown.

Now let us try these with Main() method, the code in main is like:

 

class Program
    {
        static void Main(string[] args)
        {
            Singleton obj1 = Singleton.GetInstance();
            obj1.Code = "Deepak Kamboj";
            Console.WriteLine("No. of references : " + Singleton.Reference);
            Console.WriteLine("First Objects code: " + obj1.Code);
            Singleton obj2 = Singleton.GetInstance();
            Console.WriteLine("No. of references : " + Singleton.Reference);
            Console.WriteLine("Second Objects code: " + obj2.Code);
            Singleton2 obj3 = new Singleton2();
            Singleton2 obj4 = new Singleton2();

        }
    }

First we called GetInstance() and took the reference to the new object in obj1. The code for this object is changed to Faraz Rasheed which was Maasoom Faraz by default. Then, we check for number of references to this object and code set for this. Next, we get another reference to this object through GetInstance() in obj2. We again check the number of references and code using this reference. If both the references are pointing to the same shared object, the number of references now should be 2 while the code should also be Faraz Rasheed (remember if obj2 points to a new object then code would have been Maasoom Faraz, the default one) which is shown in the output.

We also made an object of Singleton2. When constructor is called for the first reference (obj3), the new object is instantiated printing the message on Console. But when another instance of Singleton2 is attempted to be made through obj4, an exception is thrown saying Singleton class can only be instantiated once.

Sample output from the program is:

No. of references : 1
First Objects code: Deepak Kamboj
No. of references : 2
Second Objects code: Deepak Kamboj
Creating First Object of Singleton2 class...

Unhandled Exception: System.Exception: This class is Singleton,so only one object of it can be instantiated. 
at Singleton.Singleton2..ctor() in c:\documents and settings\msff\my documents\visual studio projects\singleton\class1.cs:line 75 
at Singleton.Client.Main(String[] args) in c:\documents and settings\msff\my
documents\visual studio projects\singleton\class1.cs:line 20
Press any key to continue

The complete source code is also attached with the article. Take a look at it to understand it to full. 

Conclusion:

By using Singleton Design Pattern, it is possible for a programmer to control the instantiation of class by allowing only single object to be instantiated when desirable.

Backtrack: http://www.c-sharpcorner.com/UploadFile/faraz.rasheed/SingletonPattern12052005063955AM/SingletonPattern.aspx


  • Permanent link to this post Permalink 
  • Share this post! Share It! 
  • View this post's comments Comments (57) 
  • RSS Feed for this post's comments Comment RSS
  •    


Comments

Comments

November 9. 2009 10:18 AM

cash loan

Just wanted to say thanks for this.

cash loan

November 18. 2009 04:23 PM

payday loans

Just try to smile for about 2-3 mins then you can get back to work

payday loans

November 20. 2009 04:43 AM

payday loans

I guess there's always an easier way ...

payday loans

November 24. 2009 02:41 AM

cash loans

Like your writing! Still you can do some things to improve it.

cash loans

January 18. 2010 10:18 AM

Loans in OK

Winners take time to relish their work, knowing that scaling the mountain is what makes the view from the top so exhilarating.

Loans in OK

February 2. 2010 12:22 PM

payday loans

It is a rough road that leads to the heights of greatness.

payday loans

March 16. 2010 06:35 AM

instant approval payday loans

I keep listening to the news talk about getting free online grant applications so I have been searching around for the best site to get one.

instant approval payday loans

March 17. 2010 01:51 PM

bad credit cash advance

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

bad credit cash advance

March 20. 2010 09:59 AM

fast approval loans

Hey, i've been reading this blog for a while and have a question, maybe you can help... it's how do i add your feed to my rss reader as i want to follow you. Thanks.

fast approval loans

March 21. 2010 12:47 AM

fast bad credit loans

Please, can you PM me and tell me few more thinks about this, I am really fan of your blog...

fast bad credit loans

March 23. 2010 04:11 PM

stretch mark remover

Of course, what a great site and advisory posts, Can I add backlink - import your rss feed? Regards, Reader.

stretch mark remover

April 20. 2010 06:30 AM

watch full length movies online

Thank you for this helpfull review. It really was helpfull. Keep up the good work.

watch full length movies online

April 21. 2010 08:04 AM

need a loan

That is some inspirational stuff. Never knew that opinions could be this varied. Thanks for all the enthusiasm to offer such helpful information here.

need a loan

April 28. 2010 05:29 AM

free payday loans

Keep working ,great job!

free payday loans

May 2. 2010 02:42 AM

Pa Sturtz

Pa Sturtz

May 8. 2010 11:39 PM

Paris Boga

Just wanted to grant you a shout from the valley of the sunlight, skillful information. Much appreciated.

Paris Boga

May 14. 2010 01:57 PM

poor credit personal loan

I don't like your template but your posts are quite good so I will check back!

poor credit personal loan

May 24. 2010 03:00 PM

doe-fobr

The design of the famous stylist, most popular style in the world . you have a wide choice and let people surprises. Often come here is a enjoyment.www.dior-store.com  I know some website the same to the post, you can to see. Such a. Is the leading of fashion.

doe-fobr

May 24. 2010 08:40 PM

dead-moon.com

I am quite agreen with the write's says about the experiencial knowledge of better living.For home improvement I have glance those sits.I found they benifit for life. I want to buy something to home use. Hope you give me a good views www.salenewbalance.com

dead-moon.com

May 24. 2010 08:40 PM

dead-moon.com

I am quite agreen with the write's says about the experiencial knowledge of better living.For home improvement I have glance those sits.I found they benifit for life. I want to buy something to home use. Hope you give me a good views www.salenewbalance.com

dead-moon.com

May 25. 2010 10:28 AM

profit instruments review

Precise unpredicted.

profit instruments review

May 26. 2010 05:04 AM

bape sale

I am very interested in the write's view on the leisure. As people's living conditions are increasingly favorable, diversified recreations are accepted by people. Here are some sits can buy to leisure-related products.
www.13.speaking-words.com

bape sale

June 1. 2010 02:41 PM

moncler

"Here elaborates the matter not only extensively but also detailly .I support the
write's unique point.It is useful and benefit to your daily life.You can go those
sits to know more relate things.They are strongly recommended by friends.Personally
I feel quite well.
www.moncler-jackets-outlet.com/moncler-men.html

moncler

June 12. 2010 07:18 PM

instant personal loans

What simple action could you take today to produce a new momentum toward success in your life?

instant personal loans

June 15. 2010 12:34 AM

moncler

"It looks good,I have learn a recruit!
Recently,I found an excellent online store, the XX are completely various, good quality and cheap price,it’s worth buying!
www.moncler-down-jackets.com

moncler

June 19. 2010 05:42 AM

down jackets

Well , the view of the passage is totally correct ,your details is really  reasonable and  you <a href=" http://in-the-information.com/ " >wslmart.net </a> guy give us  valuable  informative post, I totally agree the standpoint of upstairs. I often surfing on this forum when I m free and I find there are so much good information we can learn in this forum!

down jackets

June 23. 2010 11:44 AM

air force 1 shoes

The post of content is very interesting and exciting. I learned <a href="http://www.air-jordan-20.com" >air jordan 20</a>  a lot from here.The content from simple to complex, so all of you can come in . No matter you want to see what can be found.By the way ,there are some websites <a href="http://www.air-jordan-19.com" >air jordan 19</a>  is also very wonderful,you can go and see.such asXXXXX.

air force 1 shoes

June 24. 2010 01:25 AM

scabies pictures

Hello, maybe this is off topic but anyway, i've been browsing around your site and it looks really really neat. I'm building a new blog and struggling to make it look good, everytime i touch something i mess it up. How hard was it to build your site? Could someone like me with no experience do it, and add family update pages without wrecking it every time?

scabies pictures

June 24. 2010 10:05 PM

fleas on humans

good good�this post deserves nothing �hahaha just joking Tong �nice post Tong

fleas on humans

June 25. 2010 08:41 AM

Acer Aspire One

I have a awesome sense of humor and I enjoy laughing the wacky of her jokes.

Acer Aspire One

June 25. 2010 11:09 AM

Swing Sets Accessories

I'm going to cite this post in a thesis for my graduate studies. Please email me if that's okay and if you would like a copy of the document. Naturally I will give you the appropriate citations.Obviously I will cite your articleI believe you are a highly credible source on the subject.

Swing Sets Accessories

June 26. 2010 02:53 AM

Yogurt Maker

Please, can you PM me and tell me few more thinks about this, I am really fan of your blog...gets solved properly asap.

Yogurt Maker

June 26. 2010 04:43 AM

lip gloss

This website is organic! Most on the time when i stop by weblogs, I engage into intense advertisements that give me nothing, but this time when I came accross into your site and I used to be stunned. You are giving out some skilled info. Please preserve it up!

lip gloss

June 26. 2010 12:20 PM

Motorola DROID

Thankfully, Amoils has an all natural skin tag removal product that can get rid of your skin tags safely and with no pain.  And unlike other skin tag removal techniques, Amoils won't leave you with any scars.  Also, the skin tags won't return after the skin tag removal is finished.

Motorola DROID

June 26. 2010 01:03 PM

I-Phone 3G-3GS

Sometimes I just think that people write and dont really have much to say.  Not so here.  You definitely have something to say and you say it with style, my man!  You sure do have an interesting way of drawing people in, what with your videos and your words.  Youve got quite a one-two punch for a blog!

I-Phone 3G-3GS

June 28. 2010 01:57 AM

Cisco Linksys

This is actually really interesting regarding your fact article here, This article is very informative.

Cisco Linksys

June 29. 2010 08:25 PM

lose stomach weight

No wherever for the website named Eating habits max cleanse was there an email to make use of to produce contact  the phone range didna  t seem to exist 1-866-889-2187  so the panic did begin to set into the pit of my tummy  I easily got onto google and literally typed inside my lookup bar a oehow to phone this quantity 1-866-889-2187 from australiaa   and this incredible useful internet site we're on proper now  appeared

lose stomach weight

July 1. 2010 07:27 AM

Jual Beli Barang

Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here

Jual Beli Barang

July 2. 2010 08:14 AM

make money online

Greetings from Ohio!  Just saw your posts.  Actually read your article, I'll pass it along! Frown   Have a good day!

make money online

July 3. 2010 02:12 PM

celebrity gossip

Great Site for investing articles and posts. Really enjoyed it alot and plan on coming returning, so keep up the good work!

celebrity gossip

July 5. 2010 06:36 PM

gosip artis

Of course, what a great site and informative posts, I will add backlink - bookmark this site? Regards, Reader.

gosip artis

July 11. 2010 09:04 AM

amazon coupons

amazon coupons

amazon coupons

July 11. 2010 10:55 PM

lenen zonder bkr toetsing

BKR problemen? Nu Geld lenen zonder BKR toetsing? Op zoek naar betrouwbare aanbieders? Wij vergelijken banken die u toch kunnen helpen aan een betrouwbare

lenen zonder bkr toetsing

July 12. 2010 01:54 AM

lenen zonder bkr toetsing

BKR problemen? Nu Geld lenen zonder BKR toetsing? Op zoek naar betrouwbare aanbieders? Wij vergelijken banken die u toch kunnen helpen aan een betrouwbare

lenen zonder bkr toetsing

July 16. 2010 02:24 PM

Walter

sagabindara salutes you all out there

Walter

July 22. 2010 06:56 AM

migraine

Migraine Gedetailleerde en berouwbare info Tips, oorzaken en behandelmethodes!

migraine

July 22. 2010 03:13 PM

migraine

Migraine? Start hier de Hoofdpijn Zelftest. Ontdek wat je er tegen kunt doen!

migraine

July 30. 2010 01:35 AM

lenen

Over de voor- en nadelen van het afsluiten van een lening zonder BKR-toetsing.

lenen

July 30. 2010 11:47 AM

free porn

Ninety percent of everything is crap.
DQG827812234

free porn

August 2. 2010 06:34 AM

gelang

Having read the post, I have bookmarked your blog.

gelang

August 10. 2010 05:36 AM

hypotheek

Hoeveel kan ik lenen? (hypotheek). Wat worden mijn maandlasten? (hypotheek) ... Hoeveel hypotheek heb ik nodig? Hoe hoog is de boete die ik nu zou moeten

hypotheek

August 10. 2010 09:15 AM

hypotheek

Bereken zelf uw hypotheek. Hypotheek berekenen? Maak snel een indicatieve berekening van het maximale leenbedrag van uw hypotheek.

hypotheek

August 15. 2010 11:35 AM

vigrx

your site layout is very good

vigrx

August 17. 2010 01:42 AM

manga

When will you provide an update?  I would like to stay informed.  Thanks.

manga

August 18. 2010 09:28 AM

Nike Dunk

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Nike Dunk

August 24. 2010 11:16 PM

dental tooth whitening

The expense of whitened fillings can differ from  150 to  200 per teeth  If a silver filling is chipped or cracked  dentistry insurance may possibly pay for component from the expense of replacement  Replacing amalgam fillings with tooth-colored composite fillings is often a basic technique that will create a major variance as part of your giggle   Locate a Mercury-Free Tooth doctor by way of DocShop

dental tooth whitening

August 25. 2010 02:56 PM

Northwestern University Dating

Your ability to come up with innovative and original ideas makes you
perfect, Allow me to congratulate you for a job well done.

Northwestern University Dating

About Me

Deepak Kamboj

Deepak Kamboj, MCTS, JCP
ASP.NET/C# Web Developer
Chandigarh, India

RSS Contact Twitter Facebook LinkedIn

Yahoo: DeepakKamboj@yahoo.com
GTalk: DeepakKamboj@gmail.com
Skype: DeepakKamboj

Recent Comments