public sealed class Singleton
{
private static readonly Lazy<Singleton> _instance =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return _instance.Value; } }
private Singleton()
{
//Console.Write("... Singleton is created ...");
}
}
We could also use a generic template like this:
public static class Singleton<T> where T : new()
{
private static readonly Lazy<T> _instance = new Lazy<T>(() => new T());
public static T Instance { get { return _instance.Value; } }
}
and the class type to be passed:public class Car
{
public Car()
{
Console.WriteLine("Car is created");
}
}
References and further reading:
http://geekswithblogs.net/BlackRabbitCoder/archive/2010/05/19/c-system.lazylttgt-and-the-singleton-design-pattern.aspx
http://csharpindepth.com/articles/general/singleton.aspx

No comments:
Post a Comment