Tuesday, September 8, 2009

Singleton Pattern with C#

Singleton Pattern which is classified under Creational Pattern which focuses on having only one instance of object at any given time.

To give an example, windows directory service which has multiple entries but you can only have single instance of it through out the network.

  • A singleton is the sole instance of some class.
  • It is most often the case that the singleton should also be globally accessible, and this is achieved by making the creation method/property public.
  • Note that in the code below, the class constructor is private to avoind creating instance of class.
Creating Class which will return only one instance:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProject.SingletonSample.Evaluation;

namespace MyProject.SingletonSample
{
public class Singleton
{
// Private Constructor to not allow to creating instance
private Singleton() { }

private static iEvaluation instance;

// Creates and maintains single instance of Evaluation Class
public static iEvaluation Instance
{
get
{
if (instance == null)
{
instance = new Evaluation.Evaluation();
}
return instance;
}
}

}
}


Creating Instance of Singleton class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyProject.SingletonSample.Evaluation;

namespace MyProject.SingletonSample
{
class Program
{
static void Main(string[] args)
{
EvalData ed1=new EvalData();
ed1.Name = "Aaaa";
ed1.Comment = "Added with ED1";
ed1.DateSubmitted = DateTime.Now;

EvalData ed2 = new EvalData();
ed2.Name = "Bbbb";
ed2.Comment = "Added with ED2";
ed2.DateSubmitted = DateTime.Now;

Singleton.Instance.AddEval(ed1);
Singleton.Instance.AddEval(ed2);

Console.ReadKey();
}
}
}

< Back to Design Patterns

No comments:

Post a Comment