Generics enables a whole new functionality. Combining this with the power of a singleton class creates something really interesting: a generic singleton class!
I'm using this in a project, it really helps to minimize the code!
Here's the code for the generic singleton:
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomatorGui.General
{
public class GenericSingleton<T> where T : class, new()
{
private static T instance;
public static T GetInstance()
{
lock (typeof(T))
{
if (instance == null)
{
instance = new T();
}
return instance;
}
}
}
}
Now I can create multiple instances of several classes with the same singleton class. Here's the implementation code:
DateTime lastUpdate = AutomatorGui.General.GenericSingleton<AutomatorGui.General.GeneralParams>.GetInstance().LastUpdate;
I created a singleton instance of the AutomatorGui.General.GeneralParams class and checked for the last update. Then I create an instance of the TubeParams class en check for the last TubeLastUpdate:
DateTime lastUpdate = AutomatorGui.General.GenericSingleton<AutomatorGui.General.TubeParams>.GetInstance().LastUpdate;
You can use this singleton class for all your needs. The lock function ensure thread safety!