/* The Singleton pattern assures that there is one and only one instance
of a class, and provides a global
point of access to it. There are any number of cases in programming
where you need to make sure that there can be one and only one
instance of a class. For example, your system can have only one
web service manager, or a single point of access to a
database.
The easiest way to make a class that can have only one instance is to
embed a static variable inside the class that A static
variable is one for which there is only one instance, no matter how
many instances there are of the class. To prevent instantiating the class
more than once, we make the constructor private so an instance can
only be created from within the static method of the class.
Read-only property Instance check if static variable _instance is initialized,
if not property will return the new instance od Singleton class, otherwise the
existing instance will be returned.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPatterns
{
public sealed class Singleton
{
private static Singleton _instance;
private Singleton()
{/* no code */}
public static Singleton Instance
{
get
{
if(_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
public static void SomeMethod()
{
//Do some job
}
}
}
//The Test case for this Singleton Class
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace DesignPatterns
{
public class Program
{
public static void Main(string[] args)
{
Singleton inst = Singleton.Instance;
Console.WriteLine("Singleton ID is {0}", inst.GetHashCode().ToString());
Singleton inst2 = Singleton.Instance;
Console.WriteLine("Singleton ID is {0}", inst2.GetHashCode().ToString());
Debug.Assert(inst.GetHashCode() == inst2.GetHashCode(), "ID is not the Same!");
Console.ReadLine();
}
}
}
//If you will run this quick test you will that every time the property Insance is called it returns the same object.