Singleton Design Pattern in C#
Simple Singleton Design Pattern - Not thread safe
Code Snippet showing a simple Singleton Design pattern :///
/// The 'Singleton' Design Pattern
///
{
// Define a static class variable
private static Singleton _instance;
// Have a private Constructor
private Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization.
// Note: this is not thread safe.
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
Above implementation has below advantages:
• Singleton provides lazy instantiation i.e the instantiation is not performed until an object asks for an instance. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.
•Above implementation of Singleton class 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.
Below are two approaches solve this problem.
- One approach is to use Double-Check Locking .
- Second approach is to use static initialization approach.
Singleton Design Pattern - Static Initialization
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get { return instance; }
}
}
The class is marked sealed to prevent derivation, which could add instances. The variable is marked readonly, which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.
Singleton Design Pattern - Thread safe
Code Snippet showing a Thread Safe Singleton Design pattern :///
/// The 'Singleton' Design Pattern
///
{
// Define a static class variable
private static Singleton _instance;
private static object syncRoot = new Object();
// Have a private Constructor
private Singleton()
{
}
public static Singleton Instance()
{
// Uses lazy initialization.
// Note: this is thread safe.
lock (syncRoot)
{
if (_instance == null)
_instance = new Singleton();
}
return _instance;
}
}
No comments:
Post a Comment