Created
June 4, 2012 13:27
-
-
Save Dynyx/2868369 to your computer and use it in GitHub Desktop.
Thread-safe singleton pattern
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
// In software engineering, the singleton pattern is a design pattern used to implement the mathematical | |
// concept of a singleton, by restricting the instantiation of a class to one object. This is useful when | |
// exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized | |
// to systems that operate more efficiently when only one object exists, or that restrict the instantiation | |
// to a certain number of objects. | |
public sealed class MySingleton | |
{ | |
private static MySingleton instance; | |
private static readonly Object sync = new object(); | |
private MySingleton() | |
{ | |
// initialize members here | |
} | |
public static MySingleton Instance | |
{ | |
get | |
{ | |
if (instance == null) | |
{ | |
lock (sync) | |
{ | |
if (instance == null) | |
instance = new MySingleton(); | |
} | |
} | |
return instance; | |
} | |
} | |
public void SayHello() | |
{ | |
Console.WriteLine("Hello!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment