We usually use Singleton design pattern where only one object of a class is required. It is very simple and I try to explain it.
public class MyClass
{
static MyClass myclass;
// make constructor private
// now you cannot make a direct instance of this class like:
// MyClass obj=new MyClass() // it wount compile
private MyClass()
{
}
public static MyClass GetInstance()
{
lock (typeof(MyClass))
{
if (myclass == null)
{
myclass = new MyClass();
}
}
return myclass;
}
//Destructor
~MyClass()
{
myclass = null;
}
}
Concept behind this patteren is very simple, we create a static object of a class which remains in memory until destroyed by the destructor.when we try to make another object of this class our method will check the existing instance, if already exist then retun the existing object otherwise create a new object.
Now call the static method using this line of codes
MyClass obj=MyClass.GetInstance();
if it is helpful, plese dont forget to leave a comment.
June 16, 2009 at 10:04 am
What will happen if a multithreading application tries to use this singleton construction?
Have you heard about Lock statement or any other classes from System.Threading namespace?
I would suggest something like that:
public class MyClass
{
private static MyClass myclass;
// make constructor private
// now you cannot make a direct instance of this class like:
protected MyClass()
{
}
public static MyClass Instance()
{
if (myclass == null)
{
lock (typeof(MyClass))
{
if (myclass == null)
{
myclass = new MyClass();
}
}
}
return myclass;
}
}
June 19, 2009 at 11:31 am
thanx for your suggestion, i have updated my post, keep visiting.