Generic Singleton pattern
namespace SingletonPattern
{
/// <summary>
/// SingletonBase with Generic constraints with class (Reference type) ,new T must have a public parameterless constructor .
/// with new constraints that the type can't be abstract.
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonBase<T> where T : class ,new()
{
private static T instance;
private static object lockingObject = new object();
public static T Instance
{
get
{
if (instance == null)
{
lock (lockingObject)
{
if (instance == null)
{
instance = new T();
}
}
}
return instance;
}
}
}
}
Person person = SingletonBase<Person>.Instance;
Woman woman = SingletonBase<Woman>.Instance;
Woman woman1 = SingletonBase<Woman>.Instance;

浙公网安备 33010602011771号