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.

Advertisements