Variations on the singleton pattern

There are some commonly used variations of the singleton pattern that are applicable based on the given situation. Out of these, the most common ones are lazy initialization and the double check locking pattern.

Lazy initialization singleton basically creates its one and only instance upon its first call to get an instance instead of pre-creating it. Refer to the following simple code sample:

    public sealed class LazySingleton 
{
private static LazySingleton instance = null;
private LazySingleton() { }

public static LazySingleton getInstance()
{
if (instance == null) instance = new LazySingleton();
return instance;
}
}

The double check locking pattern is basically a thread-safe singleton pattern in a multithreaded environment. It ensures that only one instance is created if two or more threads ask for a singleton instance at the same time using the simple synchronization technique. Refer to the following simple code sample for a better understanding:

    public sealed class DCLockingSingleton 
{
/// <summary>
/// volatile tells the compiler not to optimze this
field and a field might be modified by multiple threads
/// </summary>
private static volatile DCLockingSingleton instance = null;

/// <summary>
/// Single object instance is used to lock all the
accesses to get the instance of the Singleton
/// </summary>
private static object syncRoot = new Object();

private DCLockingSingleton() { }

/// <summary>
/// Exposed as a Get only property instead of a method
/// </summary>
public static DCLockingSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new DCLockingSingleton();
}
}

return instance;
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.35.194