Hi Guys
Following Singleton class is given in the following website
http://www.c-sharpcorner.com/UploadFile/faraz.rasheed/SingletonPattern12052005063955AM/SingletonPattern.aspx
Complete program will give better understanding. Please anyone can develop appropriate client code (Main method) for this partial Singleton class Program.
Thank you
class Singleton
{
private static Singleton instance;
private static int numOfReference;
private string code;
private Singleton()
{
numOfReference = 0;
code = "Maasoom Faraz";
}
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
numOfReference++;
return instance;
}
public static int Reference
{
get { return numOfReference; }
}
public string Code
{
get { return code; }
set { code = value; }
}
}
Posted Oct 3, 2007, 1:31 PM
Thank you very much for the explanation, Guys
chrisPosted Oct 3, 2007, 11:05 AM
Exactly. Hopefully this isn't repetitive....
The main code calls the singleton as it is. As the singleton class is a singleton, it will only have one instance. If you could create the instance of the singleton in the main code, it wouldn't be a singleton. A singleton class takes care of itself in terms of determining if it's single instance exists.
AlanPosted Oct 3, 2007, 10:51 AM
The idea is that the GetInstance() method never returns null - it always returns a reference to the singleton object - so the client doesn't need to check whether it's null or not.
In order to do this the GetInstance() method creates the singleton object the first time it is called and returns a reference to the new object. On subsequent calls, it just returns a reference to the existing object.
This way of doing things makes sense because the GetInstance() method is really a replacement for a public constructor in a 'normal' class.
Posted Oct 3, 2007, 10:41 AM
When we create an object inside the client code (Main method) we never check the object to be null.
What is the reason of checking the object that is created outside the client code? Anyone knows please explain.
AlanPosted Oct 3, 2007, 10:08 AM
If the GetInstance() method is being called for the first time, then the singleton object will not yet have been created and 'instance' will therefore be null.
So, the code checks to see whether instance is null and, if it is, creates the singleton.
Posted Oct 3, 2007, 8:41 AM
I am unable to understand why if (instance == null) in the Singleton class. Anyone knows please explain.
public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
numOfReference++;
return instance;
}
Posted Oct 2, 2007, 10:13 PM
Thank you very much for your help, Jan
Jan MontanoPosted Oct 2, 2007, 9:32 PM
{
}
Whatever you do, the Singleton variables you create will always be of the same instance, same content. If we modifiy c.Code, in effect, d.Code will also be modified. Whatever you do with one Singleton variable, will affect other Singleton variables