public static class Singleton<T> where T : class,new() { privatestatic T _Instance; privatestaticobject _lockObj = newobject(); ///<summary> /// 获取单例对象的实例 ///</summary> publicstatic T GetInstance() { // 检查1 if (_Instance != null) return _Instance; // 锁 lock (_lockObj) { // 检查2 if (_Instance == null) { // 创建实例 var temp = Activator.CreateInstance<T>(); // 原子操作:互换 System.Threading.Interlocked.Exchange(ref _Instance, temp); } } return _Instance; } }
Unity中的使用
简单懒汉
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class Singleton<T> where T : new() { static T instance; publicstatic T Instance { get { if (instance == null) { instance = new T(); } return instance; } } }