In today’s article I would like to briefly discuss one of the commonly used design pattern in software engineering which is Singleton Pattern. Singleton pattern is usually being used if you are creating a system that only needs one instance of a class and that instance will be used throughout the lifecycle of the application. Common scenarios of using Singleton pattern is for logging, database access, etc.
Let’s start by creating sample console application for just simply displaying Hello World in the screen. Let’s create a ShowMessage Class with one method called HelloWorld as shown in Figure 1.

After creating the ShowMessage Class, let’s try to consume it by creating two instances of the said class, let’s name the instance message1 and message2. Then let’s verify if message1 and message2 are of different instance of class ShowMessage by creating an if else statement as shown in figure 2.

Now let’s try to run our application and we expect to see two “Hello World” and “Objects are of different instance” due to different instantiation of message1 and message2.

So as you can see in our current setup we can create an instance of our ShowMessage Class as many as we want and we don’t have any mechanism to control it. Now let’s try to convert our ShowMessage class to Singleton pattern.
Create a private static instance of it’s Class

Make the access modifier of the constructor as private

Create a method for creating the instance of the class
The contents of the CreateInstance method is just checking if your private instance field called _instance have already been instantiated. If not, it will instantiate it and return the instance of type ShowMessage.

That’s it we already converted our class to be Singleton and let’s try to modify our Main class. Instead of using the new keyword will just directly call the CreateInstance method because it is declared as Static.

Now let’s try to run our application and see the difference from our previous Main class setup.

As you can see both message1 and message2 refers to a single instance of our Class ShowMessage. Let’s modify a little bit because in our current Singleton Pattern implementation it is prone to bugs due to it has no locking mechanism for thread safety. Let’s create a simple Locking mechanism for thread safety by adding a static readonly objectLock of type Object and then transfer the current instance checker to the Lock statement as shown in Figure 9.

Conclusion
There we have it! A simple implementation of a thread safe singleton pattern but there are also some more complex checking like the double check lock mechanism, the non-lazy thread safe implementation, full lazy implementation and Lazy<T> type implementation. Another thing to keep in mind is that there are already frameworks that provide Singleton pattern like the one I used before called MvvmCross another one is Prism framework.
Happy Coding 🙂