Singleton pattern in CSharp

Source: Internet
Author: User
Singleton pattern in CSharp
Level Author
Beginner Kunal Cheda

Singleton assures that there are one and only one instance of the class and provides a global point of access to it. There are number of cases in programming where your need to make sure that There can be one and only one instance of a Clas s e.g Window Manager,print Spooler etc.

Points to the Example constructor of Class B are private not allowing other classes to Create the Instance. Class B has a private static variable (x) which would have the one and one Instance of the Class B, and can be accessed thro Ugh Static method Getb. If Getb is accessed for the ' the ' the ' the ' the ' the ' the ' the ' the ' the ' is ' is null, and would create the Instance and return x, from next requests TB method It would simply return X.

Save the file as Singleton.cs, Compile C:\>CSC Singleton.cs and Run C:\>singleton

CODE

Singleton.cs

Using System;
Class A
{
public static void Main (String [] args)
{
B m = B.getb ();
m.j=100; Make changes to instance variable J
Console.WriteLine (M.J);
B x = B.getb ();

X.J print ' s which means that there are one and only one Instance
Console.WriteLine (X.J);

}
}

Class B
{
private static B x;
public int j= 0;
Private B ()
{
}
public static B Getb ()
{
if (x==null)
{
X=new B ();
}
return x;
}
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.