Created
September 13, 2016 18:34
-
-
Save OmegaExtern/6c38e89240f247bbb811b6217c1a6d61 to your computer and use it in GitHub Desktop.
Singleton Pattern in C#.
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
#region Singleton Pattern | |
// NOTE: The class is marked as sealed to prevent the inheritance of the class (i.e. use it as base/super class). | |
internal sealed class Singleton | |
{ | |
private static readonly object SingletonSyncRoot = new object(); | |
private static volatile Singleton _instanceSingleton; | |
// NOTE: Default/Parameterless constructor is private to prevent instantiation of the class. | |
private Singleton() | |
{ | |
} | |
public static Singleton Instance | |
{ | |
get | |
{ | |
// Double-checked locking pattern. | |
if (_instanceSingleton != null) | |
{ | |
return _instanceSingleton; | |
} | |
lock (SingletonSyncRoot) | |
{ | |
return _instanceSingleton ?? (_instanceSingleton = new Singleton()); | |
} | |
} | |
} | |
} | |
// NOTE: The class is marked as sealed to prevent the inheritance of the class (i.e. use it as base/super class). | |
internal sealed class EagerSingleton | |
{ | |
// NOTE: Default/Parameterless constructor is private to prevent instantiation of the class. | |
private EagerSingleton() | |
{ | |
} | |
// CLR eagerly initializes static member when the class is first used | |
// CLR guarantees thread-safety for static initialization | |
public static EagerSingleton Instance | |
{ | |
get; | |
} = new EagerSingleton(); | |
} | |
#endregion Singleton Pattern |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment