Singleton Pattern in C#

Implementing the Gang of Four Singleton Pattern in Microsoft’s C# .NET language is nearly identical to its Java implementation. The Singleton Pattern (as definied by the Gang of Four in 1995) is to “ensure a class only has one instance, and provide a global point of access to it.”

The idea behind the Singleton pattern is that there can only be one unique object of the class in existence at any one time. To make this possible we must make the constructor private and instead create a public “get” accessor for the Instance reference that controls access to the constructor, returning a new object if none exists or returning the already instantiated object if one does.

Here we have an example of the simplest possible Singleton class which I call, Singleton. It has only those methods absolutely necessary for the pattern and one console print statement in the constructor so that we can easily see when the constructor is called. I have opted to include Singleton and TestSingleton, its testing harness, in a single file. This allows me to easily demonstrate how to create the Singleton pattern and how to instantiate a Singleton object from outside the class.

TestSingleton.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingletonPattern
{
    class TestSingleton
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Calling First Instance: ");
            Singleton mySingleton = Singleton.Instance;
            Console.WriteLine("Calling Second Instance: ");
            Singleton myOtherSingleton = Singleton.Instance;
        }
    }
    public class Singleton
    {
        private static Singleton instance;
        private Singleton()
        {
            Console.WriteLine("Singleton Constructor Called");
        }
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

Microsoft has a great article discussing the Singleton Pattern and its common variations as they pertain to the C# language in the MSDN Patterns and Practices Developers Center – Implementing Singleton in C#.

Also see: Sheep Guarding Llama Singleton Pattern in Java

Singleton Pattern in Java

Implementing a Singleton Class Pattern in Java is a common and easy task. The Singleton Pattern (as definied by the Gang of Four in 1995) is to “ensure a class only has one instance, and provide a global point of access to it.”

The idea behind the Singleton pattern is that there can only be one unique object of the class in existence at any one time. To make this possible we must make the constructor private and instead create a public getInstance() method that controls access to the constructor, returning a new object if none exists or returning the already instantiated object if one does. We must also override the clone() method from the Object superclass as this oft forgotten method will provide a workaround to our Singleton protection.

Here we have an example of the simplest possible Singleton class which I call, Singleton. It has only those methods absolutely necessary for the pattern and one console print statement in the constructor so that we can easily see when the constructor is called.

Singleton.java

public class Singleton {
     private static Singleton instance;
     private Singleton() {
          System.out.println("Singleton Constructor Called");
     }
     public static synchronized Singleton getInstance() {
          if (instance == null)
               instance = new Singleton();
          return instance;
     }
     public Object clone() throws CloneNotSupportedException {
          throw new CloneNotSupportedException();
     }
}

Now that we have a working Singleton class we need to make a simple test harness to see how we can call it and how it behaves. In our test we will simply create two objects, mySingleton and myOtherSingleton and we will see when the constructor method is called.

TestSingleton.java

public class TestSingleton {
        public static void main (String[] args) {
                System.out.print("Calling First Instance: ");
                Singleton mySingleton = Singleton.getInstance();
                System.out.print("Attempting to Call Again: ");
                Singleton myOtherSingleton = Singleton.getInstance();
        }
}

Hopefully this will help you write quick and easy Singleton pattern classes in the future.

See also: Sheep Guarding Llama Singleton Pattern in C#

May 8, 2008: Beginning My Programming Project

I had to play catch-up with the SGL posts today. I was running a little bit behind. I didn’t have a chance to even open the editor yesterday and May 5th was still sitting in my “drafts”. But I got caught up. Now that my huge Red Hat exam project is over I am able to focus on more things and get caught back up.

Brass Plaque of 1180 Raymond Boulevard, Newark

Today is a doggy-daddy day. The weather has turned dark and threatening. Not like the warm summer days we have had the last few days. It is still pretty warm but very humid and overcast.

Oreo insisted on another walk in the park today. This is his third this week taking one on Sunday, another on Tuesday and one more today. The temperature was perfect and the clouds and humidity were perfect for making the city seem almost silent. I always find it strange walking Oreo in the park in the heart of a major city, surrounded by skyscrapers, and having the world be so quiet and still. There was just the slightest drizzle as we walked through Military Park.

I forgot to mention yesterday that another Amazon order arrived. We got a pack of Rock Hudson movies and a pack of the Bob Hope & Bing Crosby classic “On the Road” movies like Road to Morocco. Classic stuff. We also got the three final episodes of the fourth season of Family Guy which are sold separately from the rest of the season. Another eBay computer arrived today as well. This one is an ultra-small form factor HP Compaq d530. Nothing special but I love these tiny form factor machines. They are just so easy to deal with.

Dominica did some light shopping on her lunch break yesterday and decided that we needed the first season of The Brady Bunch which is pretty funny to own. I suppose it will be interesting to see the show starting from the beginning. It is such a quintessential piece of the childhoods of just about anyone anywhere near my age that it is hard to think of it as being like a normal television show. And it only existed as reruns which were shown disconnected and out of order. So to many of us there was no flow whatsoever in the show. It was just a serious of vignettes. So now we will see it as an actual show and see if that improves it in any way. I think that she was thinking about The Brady Bunch as we recently saw two of the actors show up in the first season of The Love Boat and we also saw two who did a guest appearance on the final season of That 70s Show.

I wasn’t as tired today as you might think that I would be having worked so late last night. I feel so much better having so much work completed and out of the way that I really have a lot more energy.

Dominica got home and we just got simple food from the deli downstairs.  We ate and watched and episode of The Love Boat. Then Min was off to bed and I went to work on my Java project.  I am attempting to properly incorporate some basic design patterns into my project like the Model-View-Controller and Singleton patterns.  So far this project is moving along while still being quite educational.

May 7, 2008: Work, Work and More….

Work.

Today I have a Hewlett-Packard “show” in Tribeca at lunchtime running all afternoon so I decided, rather than going to downtown and then having to cross town to the show that I would just work from home until the show. It saves almost an hour of total travel time as getting to Tribeca is easier than getting to Wall in the first place. It is a good thing that I did that because I ended up having a very busy morning and did not have the time to waste traveling unnecessarily.

Trinity Church from the Street

As it was I got stuck working until forty-five minutes after I had wanted to leave for the show so there was no way that I was going to make it on time. Then, right as I arrived at the Tribeca office, I got a call and was on the phone for half an hour or more before I could even go in.

The show was good and valuable. I always enjoy these technology “catch up” events. We got cool stuff at this show too like really nice polo shirts and big flash drives. I’m all into industry swag.

After the show, which went until five, I went down and worked for a little while off of the Tribeca trading floor before heading for home. It ended up being a pretty long day.

I got back home to Newark a little before seven. I decided to skip dinner. Dominica just made herself some pasta. I have a very busy evening planned out so she just watched some Internet TV and went to bed.

I settled in, by seven, to a long evening of working on a Red Hat exam. I ended up putting in an entire eight hours on continuous starring at the screen working on the exam. I didn’t wrap up until three in the morning! Boy was I tired. but I really wanted to get this work out of the way before I switched gears to work on my big Java programming project that I have to turn in in ten days. I am so much more efficient when I am not task switching more than necessary as well as when I don’t have big workloads hanging over my head. It was a long night but I did some really good work, learned a bunch of stuff as well and am feeling very happy having all of that work done and over with.

May 6, 2008: Boring Week

I have been incredibly busy lately and have been having a really difficult time keeping up with SGL as often as I would like or, more accurately, as thoroughly as I would like.

Today was a nice doggy-daddy day.  The weather was very nice and Oreo demanded that we take a long walk in Military Park.  He is so funny.  He pulls me out the front door (towards Raymond rather than Commerce) and goes up to the edge of the road and tries to pull be across to the park.  He isn’t willing to walk another way.  He knows exactly what he wants and knows how to tell me.

It was a perfect day for a walk and we had a good time.  I’m glad that the weather is so nice and that it is so easy to take him to the park.  He gets so excited.

My evening was spent mostly working on Red Hat Linux exam materials.  I’m afraid that this is a pretty boring week to be reading SGL.