Singleton class in C#
-
What is the difference between Singleton implemented using static GetInstance() method and having a Class with all Public Static methods. Is scenario#2 a Singleton class? Please let me know the differences between these two approaches. 1)----------------- public class SealedClass { private static SealedClass _class = new SealedClass(); private SealedClass() {} public static SealedClass GetInstance { get { return _class; } } } -------------------------------------- 2) public class StaticClass { public static string GetName() { return "Shubho"; } public static string GetAddress() { return "Shubho"; } }
-
What is the difference between Singleton implemented using static GetInstance() method and having a Class with all Public Static methods. Is scenario#2 a Singleton class? Please let me know the differences between these two approaches. 1)----------------- public class SealedClass { private static SealedClass _class = new SealedClass(); private SealedClass() {} public static SealedClass GetInstance { get { return _class; } } } -------------------------------------- 2) public class StaticClass { public static string GetName() { return "Shubho"; } public static string GetAddress() { return "Shubho"; } }
Interesting question. According to the GoF, the purpose of a singleton is to "ensure a class has only one instance, and provide a global point of access to it." Your second example has no instance, its just a collection of static methods and hence we couldn't get a reference to it. Microsoft has a best practice with regard to singletons - they say it should be implemented as follows - a thread safe lazy implementation
public class Singleton
{
// private constructor to prevent instantiation
private Singleton() {}private static volatile Singleton \_singleton; private static object \_lock = new object(); public static Singleton Value { get { if (\_singleton == null) { lock(\_lock); { if (\_singleton == null) \_singleton = new Singleton(); } } return \_singleton; } }
}
Regards, Rob Philpott.