I have some confusion with singleton class, below are my some points:
- Can singleton class have static method?,if yes then how we call that methods?
- what is main difference between Static class and Singleton Class?
I have created my singleton class as follows:
public class Singleton
{
private static Singleton _instance = null;
private static object chekLock = new object();
private Singleton()
{}
public static Singleton Instance
{
get
{
lock (chekLock)
{
if (_instance == null)
_instance = new Singleton();
return _instance;
}
}
}
public static void StaticAddMethod()
{
Console.WriteLine("Add Method");
}
public void AddMethod()
{
Console.WriteLine("Add Method");
}
}
In Above class structure I have created two method one is Static and second is non static, When I am trying to access Static Method it gives me compile time error.
How can I use static method of singleton class?
How are you trying to access it? To access a static method you use the type name:
vs
Note also that there are simpler ways of implementing singletons that acheive the same effect with less locking etc.
Re the difference between singleton and static; a singleton might implement an interface, allowing you to pass it into existing code. You can also (as indeed you are doing) defer construction of a singleton (yet still allow access to the static methods that don’t involve the singleton instance). But yes: there is a lot of crossover between static and singleton.