Singleton pattern is the one of the best known pattern in the software engineering. The singleton pattern is a design pattern that is used to restrict instance of class to one object, and usually gives simple access to that instance. Most commonly, singletons don’t allow any parameters to be specified when creating the instance. Typically a requirement of singletons is that they are created lazily – i.e. that the instance isn’t created until it is first needed.

UML class diagram

singleton pattern

Implementing the singleton pattern in c#:

Not thread safety implementation: The main disadvantage of this implementation is not thread safety, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created:


Thread safety implementation: To avoid the above scenario we could use the lock and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time – by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.
using System;

Conclusion: There are various different ways of implementing the singleton pattern in C#. I would prefer the second approach i.e. thread safety. Select the best approach based on the requirements.


Similar Topics: