The singleton pattern is simple enough to understand but you end up writing the same boiler plate code each time. Time to extract it into a generic class, write once use many times :)
So here is the classic singleton pattern in C#.
public class MySingleton
{
private static MySingleton _instance = null;
MySingleton() {}
public static MySingleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
// other stuff here
}
Simple enough but has to be re-implemented each time.
Enter generics to the rescue :)
public static class Singleton<T>
where T : new, class
{
private static T _instance = null;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = new T();
}
return _instance;
}
}
}
And to use it...
public class Thing() {}
public class AnotherThing() {}
var singletonThing1 = Singleton<Thing>.Instance;
var singletonThing2 = Singleton<AnotherThing>.Instance;
So what is going on here. When you stack generics on statics you end up with a separate static instance for each generic type you use.
Feel free to ask any questions :)
Happy coding
Woz