Best known Creational Design Pattern is Singleton. We can implement this pattern in different ways. I am explaining some of the ways where we can implement in C#.
We will have the following concepts in implementing the Singleton pattern
- We declare a private constructor which prevents other classes to create an instantiation of the singleton class. It also prevents the sub classing.
- We declare a class as sealed so that it can not be instantiated.
- We declare a static variable for holding the reference of a singleton class.
- We declare a public property to return the singleton instance.
- We declare a method for returning the message from the singleton class.
The problem with the above code is it is not a thread –safe code. For example if two threads evaluates the if condition in the above code and both returns the true.
We will rewrite the code for thread safety
The above implementation is thread safe but having the performance issue.
Every time the lock is acquired whenever you request the object.
We can write the above code with out implementing the locks as follows
The static constructor in C# only be called whenever you create a instance for the class.