Thomas Thomas -4 years ago 124
C# Question

what is the advantage of Singleton Design Pattern

every one know how to write code for Singleton Design Pattern.say for example

public class Singleton
{
// Private static object can access only inside the Emp class.
private static Singleton instance;

// Private empty constructor to restrict end use to deny creating the object.
private Singleton()
{
}

// A public property to access outside of the class to create an object.
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}


it is very clear that when we create a instance of any class many time the memory is allocated for each instance but in case of Singleton design pattern a single instance give the service for all calls.

1) i am bit confuse and really do nor realize that what are the reasons...that when one should go for Singleton Design Pattern. only for saving some memory or any other benefit out there.

2) suppose any single program can have many classes then which classes should follow the Singleton Design Pattern? what is the advantage of Singleton Design Pattern?

3 in real life apps when should one make any classes following Singleton Design Pattern?
thanks

Here is thread safe singleton



public sealed class MultiThreadSingleton
{
private static volatile MultiThreadSingleton instance;
private static object syncRoot = new Object();

private MultiThreadSingleton()
{
}

public static MultiThreadSingleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new MultiThreadSingleton();
}
}
}

return instance;
}
}
}

Answer Source

To assure only one and same instance of object every time.

Take a scenario, say for a Company application, there is only one CEO. If you want to create or access CEO object, you should return the same CEO object every time.

One more, after logging into an application, current user must return same object every time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download