Singleton Pattern
Summary: When it makes sense to only hae one instance of a component in the system, or the construction is expensive, or we want to prevent aditional copies creation.
Sample Code
Singleton Class
public sealed class Singleton
{
public long Ticks { get; private set; }
public static Singleton Instance { get { return lazy.Value; } }
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton> (() => new Singleton());
private Singleton()
{
this.Ticks = DateTime.Now.Ticks;
}
}
Usage
WriteLine(Singleton.Instance.Ticks);
WriteLine(Singleton.Instance.Ticks);
WriteLine(Singleton.Instance.Ticks);
Comments
Post a Comment