Sometimes it must be singleton and sometimes it must be generic, but what if it must be a generic singleton?
Within the last days I thought about a good solution for a generic singleton class. I use this class to build a usefull and small datastore solution.
Here is my idea for a generic singleton using a mutex to lock the object for the data access.
public class DataStore<T> where T : new()
{
static Mutex mutex = new Mutex();
static DataStore<T> instance;
private List<T> cache;
private DataStore()
{
cache = new List<T>();
}
public static T Instance
{
get
{
mutex.WaitOne();
if (instance == null)
{
instance = (DataStore<T>)Activator.CreateInstance(typeof(DataStore<T>));
}
mutex.ReleaseMutex();
return instance;
}
}
}