Wednesday, March 30, 2016

Singleton Pattern

Singleton Pattern 
  • a class only allow single instance of itself to be created.
  • Not allow parameters to be specified when creating instance.(Problem when second request for an instance with different parameter)
  • single constructor, private and no parameter.
  • No sub classing (it may subclass more than 1 , subclass can create an instance)

public class SingletonTest
{
        private static readonly Lazy<SingletonTest> lazy =
                 new Lazy<SingletonTest>(() => new SingletonTest());

        public static SingletonTest Instance { get { return lazy.Value; } }

        public bool Test()
        {
            return true;
        }

        private SingletonTest()
        {
        }

}


//Calling SingleTon
private SingletonTest testsingle = SingletonTest.Instance;

protected void Page_Load(object sender, EventArgs e)
{
var test = testsingle.Test();
var test2 = SingletonTest.Instance.Test();
}

________________________________________________________________________

Version 2 

public class CoffeeMachine
{
    private CoffeeMachine()
    {
    }

    public static CoffeeMachine _instance = null;

    public static CoffeeMachine Instance
    {
        get
        {
            if (_instance == null)
                _instance = new CoffeeMachine();

            return _instance;
        }
    }

}

No comments:

Post a Comment