everyone knows how to write code for Singleton Design Pattern.say for example
public class Singleton {
it is very clear that when we create an instance of any class, allocating memory for each instance many times, but in the case of the Singleton design pattern, one instance provides a service for all calls.
1) I'm a little confused and really don't understand what the reasons are ... what, when to go for the Singleton design pattern. just to save some memory or any other advantage there.
2) suppose that in any one program there can be many classes, which classes should follow the Singleton design pattern? What is the advantage of the Singleton design pattern?
3 in real applications, when do you need to do any classes after the Singleton design pattern? thanks
Here is a 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; } } }
source share