-
-
Save alexnum/2f5a6ad6c3a5016658549513db7fcf9f 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