Well it’s my first blog post on my brand spanking new site, and it’s going to be a Software Development related one.

 

Recently, at work, I came across the need to create a single instance of a class, and to then restrict anymore instances of that class being created. I struggled to find the answer, until my colleague made me aware of a little gem called the Singleton class.

 

If you haven’t heard of it before, let me explain… The Singleton class is basically a class with a private constructor, that uses a public method to instantiate the class or return the current instance. By using this method, it ensures that only one instance of the class exists in your application at any one time.

 

To the code (in C# .NET):

class Singleton { // Private instance of class private static Singleton objUniqueInstance; private Singleton() {} public static Singleton GetInstance() { if(objUniqueInstance === null) { objUniqueInstance = new Singleton(); } return objUniqueInstance; } }

 

Then to create or retrieve an instance of the class, simply:
Singleton objSingleton = Singleton.GetInstance();

 

It’s that simple. Now you have a unique instance of the class and no additional instances will ever occur.

 

Hope some of you will find this useful!

Add This!