Last active
October 8, 2019 07:34
-
-
Save soraphis/c21319d90ed5043c7556f8f7ef27637d to your computer and use it in GitHub Desktop.
generic version of thread safe singletons based on: https://csharpindepth.com/Articles/Singleton
This file contains hidden or 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
// --------------------------------------------------------------------------------------------- | |
// SOME UTILY CLASSES | |
// --------------------------------------------------------------------------------------------- | |
public abstract class ThreadSafeSingleton<T> where T : ThreadSafeSingleton<T>, new() | |
{ | |
static ThreadSafeSingleton(){} | |
protected ThreadSafeSingleton() { } | |
public static T Instance { get; } = new T(); | |
} | |
public abstract class LazyThreadSafeSingleton<T> where T : LazyThreadSafeSingleton<T>, new() | |
{ | |
protected static readonly Lazy<T> lazy = new Lazy<T>(() => new T()); | |
protected LazyThreadSafeSingleton() { } | |
public static T Instance => lazy.Value; | |
} | |
// --------------------------------------------------------------------------------------------- | |
// USAGE EXAMPLE | |
// --------------------------------------------------------------------------------------------- | |
public sealed class STestClass1 : ThreadSafeSingleton<STestClass1> | |
{ | |
public readonly int i = 3; | |
} | |
public sealed class STestClass2 : LazyThreadSafeSingleton<STestClass2> | |
{ | |
public readonly int i = 4; | |
} | |
class SomeClass { | |
static void Main(string[] args) | |
{ | |
Console.WriteLine(STestClass1.Instance.i); | |
Console.WriteLine(STestClass2.Instance.i); | |
} | |
} | |
// --------------------------------------------------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment