Know about Singleton Class

If you want to create only one instance of the class, you will go for
Singleton class.

The following is the creation and demonstration of singleton class

Name space


using System;


Code for Singleton class

sealed class MySingletonClass {
private static bool MyInstanceFlag = false;
public static MySingletonClass GetMySingletonClass() {
if (!MyInstanceFlag) {
MyInstanceFlag = true;
return new MySingletonClass();
} else {
throw new Exception("An instance of the class has already been created!");
}
}

private MySingletonClass() {
Console.WriteLine("This is My Singleto Class");
}
}


Code Explanation

1. Create a static Flag
2. Create the method GetMySingletonClass which will check the whether the instacnce created or not
3. If created it will through error message
4. If not created it will create the instance of the class
i.e will execute the code block of the constuctor

Client Code to demonstration of singleton class

class Client {

static void Main(string[] args) {
Console.WriteLine("Attempting to get first instance of the Singleton class");
try {
MySingletonClass MyFirstInstance = MySingletonClass.GetMySingletonClass();
} catch (Exception e) {
Console.WriteLine(e.Message);
}

Console.WriteLine("Attempting to get second instance of the Singleton class");
try {
MySingletonClass MySecondInstance = MySingletonClass.MySingletonClass();

} catch (Exception e) {
Console.WriteLine(e.Message);
}

}
}


Code Explanation

1. Create the First instance. It will show the message in the constructor "This is My Singleton Class"
2. Create the second instance. It will show the error message
"An instance of the class has already been created!"


By
Nathan


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: