核心代码,线程安全
class SingletonFactory<T> where T : new()
{
private static T uniqueInstance;
private static readonly object locker = new object();
public static T GetInstance()
{
if (uniqueInstance == null)
{
lock (locker)
{
if (uniqueInstance == null) uniqueInstance = new T();
}
}
return uniqueInstance;
}
}
测试类
class Person
{
public string Name { get; set; }
}
class Cat
{
public string Name { get; set; }
}
测试代码
static void Main(string[] args)
{
var obj1 = SingletonFactory<Person>.GetInstance();
obj1.Name = "张三";
var obj2 = SingletonFactory<Person>.GetInstance();
obj2.Name = "李四";
Console.WriteLine($"obj1=obj2 :{ReferenceEquals(obj1, obj2)}");
var obj3 = SingletonFactory<Cat>.GetInstance();
obj3.Name = "咪咪";
Console.WriteLine($"obj1=obj3 :{ReferenceEquals(obj1, obj3)}");
Console.ReadKey();
}
结果