Singleton Pattern Code Review
Code Download
Define the Singleton Object
Define the Singleton class with the required getInstance() method used to create a single instance of the class (object).
class Singleton
{
private static Singleton instance = null;
private static Object syncLock = new Object();
public String Item { get; set; }
private Singleton() {}
public static Singleton getInstance()
{
if (instance == null)
{
lock (syncLock)
{
if (instance == null)
{
Console.WriteLine("****** Creating Singleton instance ******");
instance = new Singleton();
}
}
}
return instance;
}
}
Use the Singleton Pattern
The Program class creates two instances of the Singleton class (object) and compares these instances to prove they are identical
and that only one version of the class (object) exists.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Getting singleton 1.");
Singleton instance1 = Singleton.getInstance();
instance1.Item = "Hello World!";
Console.WriteLine(String.Format("Got singleton 1 {0}.", instance1));
Console.WriteLine("\nGetting singleton 2.");
Singleton instance2 = Singleton.getInstance();
instance2.Item = "Foo";
Console.WriteLine(String.Format("Got singleton 2 {0}.", instance1));
if (instance1 == instance2)
{
Console.WriteLine("\nInstance 1 and Instance 2 are equal");
}
Console.WriteLine(String.Format("Instance 1, Item = {0}.", instance1.Item));
Console.WriteLine(String.Format("Instance 2, Item = {0}.", instance2.Item));
Console.Read();
}
}