Thursday, 29 September 2016

Private Constructor


Private Constructor : We can declare a constructor private  also ,this is a special instance constructor. Classes that contain static members only are generally used
Private construtor . By setting the access modifier to private it make clear that the constructor can not be instantiated .Generally in designed pattern , Singleton pattern
Follow the rule , where class constructor is private .This make sure in a whole solution only one instance of class can be created.

Example 1:
public class classB
{
    public int A; // Instance field
       public classB()
       {
              //
              // TODO: Add constructor logic here
              //
       }
    private classB() // This is the private constructor
    {
        this.A = 5;
    }
}

Example 2: Designed Patterns
//Create a singleton class
public sealed class myClass
{
    private static myClass instance = null;
    private static readonly object instancelock = new object();

    public myClass() //general constructor
    {
    }

    public static myClass Instance
    {
        get
        {
            lock (instancelock)
            {
                if (instance == null)
                {
                    instance = new myClass();
                }
                return instance;
            }
        }
    }
}


//Calling instance of class
    protected void Button1_Click(object sender, EventArgs e)
    {
        var instance1 = myClass.Instance;
        var instance2 = new myClass();
    }
    //only one instance of this class is possible

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...