Last active
September 25, 2020 09:35
-
-
Save ravage/833d5b98fbb0d5e721bf7d5c0cbb7072 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Not thread safe | |
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed | |
public sealed class Singleton { | |
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static | |
private static Singleton instance = null; | |
// hide constructor from public interface | |
private Singleton() {} | |
public static Singleton Instance { | |
get { | |
if (instance == null) { | |
instance = new Singleton(); | |
} | |
return instance; | |
} | |
} | |
} | |
// Thread safe | |
public sealed class Singleton { | |
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly | |
private static readonly Singleton InstanceHolder = new Singleton(); | |
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors | |
static Singleton() {} | |
private Singleton() {} | |
public static Singleton Instance => InstanceHolder; | |
} | |
// Thread safe & Lazy | |
// https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1 | |
public sealed class Singleton { | |
private static readonly Lazy<Singleton> InstanceHolder = new Lazy<Singleton>(() => new Singleton()); | |
private Singleton() {} | |
public static Singleton Instance => InstanceHolder.Value; | |
} | |
// Generic Singleton | |
// For the sake of example only since it defeats the singleton purpose (the is no control over T's implementation) | |
public sealed class Singleton<T> where T : new() | |
{ | |
private static readonly Lazy<T> InstanceHolder = new Lazy<T>(() => new T()); | |
private Singleton() {} | |
public static T Instance => InstanceHolder.Value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment