Skip to content

Instantly share code, notes, and snippets.

@stevomccormack
Last active May 15, 2018 07:20
Show Gist options
  • Save stevomccormack/526ab6d271a7d16c2d104b0a446fd389 to your computer and use it in GitHub Desktop.
Save stevomccormack/526ab6d271a7d16c2d104b0a446fd389 to your computer and use it in GitHub Desktop.
Singleton Design Pattern - for single & multi-thread environment
namespace Patterns.Threading
{
/// <summary>
/// Singleton Design Pattern for multi-thread environment
/// </summary>
/// <remarks>Uses double-checked locking method - effective but expensive locking mechanism with least control.</remarks>
public sealed class DoubleLockSingleton
{
private static readonly object _sync = new object();
private static DoubleLockSingleton _instance;
private DoubleLockSingleton()
{
}
public static DoubleLockSingleton Instance
{
get
{
if (_instance != null)
return _instance;
lock( _sync )
{
_instance = new DoubleLockSingleton();
return _instance;
}
}
}
}
}
using System;
namespace Patterns
{
/// <summary>
/// Singleton Design Pattern for single thread environment
/// </summary>
/// <remarks>Uses lazy instantiation method.</remarks>
public sealed class LazySingleton
{
private static readonly Lazy<LazySingleton> Lazy = new Lazy<LazySingleton>(() => new LazySingleton());
private LazySingleton() { }
public static LazySingleton Instance => Lazy.Value;
}
}
using System.Threading;
namespace Patterns.Threading
{
/// <summary>
/// Singleton Design Pattern for multi-thread environment
/// </summary>
/// <remarks>The monitor mechanism gives the greatest control over locking use cases.</remarks>
public sealed class MonitorSingleton
{
private static readonly object _sync = new object();
private static MonitorSingleton _instance;
private MonitorSingleton()
{
}
public static MonitorSingleton Instance
{
get
{
if (_instance != null)
return _instance;
Monitor.Enter(_sync);
var single = new MonitorSingleton();
Interlocked.Exchange(ref _instance, single);
Monitor.Exit(_sync);
return _instance;
}
}
}
}
namespace Patterns
{
/// <summary>
/// Singleton Design Pattern for single thread environment
/// </summary>
/// <remarks>Basic use case for singleton.</remarks>
public sealed class Singleton
{
private static Singleton _instance;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (_instance != null)
return _instance;
_instance = new Singleton();
return _instance;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment