Monday, August 1, 2011

CoolTuts - C#.Net - Singleton Design Pattern

Definition:
Ensure a class has only one instance and provide a global point of access to it.

Objectives:
  1. Hide the default constuctor so that the class cannot be instantiated from outside of the class.
  2. Create a custom constructor which returns the single instance of the object, once it is instantiated.
  3. Add a shared variable referencing the the single instantiated instance of the class.
class Program
{
static void Main(string[] args)
{
Singleton a = Singleton.Instance();

//Add a shared variable referencing the the
//single instantiated instance of the class.
a.FullName = "Emmaneale Mendu";

Singleton b = Singleton.Instance();
Console.WriteLine("My FullName is {0}",b.FullName);

Singleton c = Singleton.Instance();
Console.WriteLine("My FullName is {0}", c.FullName);

if (b == c)
Console.WriteLine("Two Instances are same");

Console.ReadKey();
}
}

public class Singleton
{
private static Singleton self;
private string name;

//Hide the default constuctor so that the class
//cannot be instantiated from outside of the class.
private Singleton() { }

//Create a custom constructor which returns the single
//instance of the object, once it is instantiated.
public static Singleton Instance()
{
if (self == null)
self = new Singleton();
return self;
}

public string FullName
{
get { return name; }
set { name = value; }
}
}

Hence I conclude that only one instance is created and only when the instance is needed.

No comments:

Post a Comment