using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XiaoZhiSharp.Kernels { [Obsolete] public class SingletonProviderUnsafe where T : new() { SingletonProviderUnsafe() { } public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } } /// /// 静态属性是有先后顺序的,如果在静态属性中使用了其他静态属性,那么被引用的静态属性必须在引用的静态属性之前定义。 /// 单例模式 /// /// public class SingletonProvider where T : new() { private static T m_instance; private static readonly object sync = new object(); private SingletonProvider() { } /// /// 用法:SingletonProvider.Instance 获取该类的单例 /// public static T Instance { get { if (m_instance == null) { lock (sync) { if (m_instance == null) { //Console.WriteLine("创建了一个对象 "); m_instance = new T(); } } } return m_instance; } } } /// /// 泛型单例基类 /// 静态属性是有先后顺序的,如果在静态属性中使用了其他静态属性,那么被引用的静态属性必须在引用的静态属性之前定义。 /// /// public class Singleton where T : class { // 使用Lazy确保线程安全的延迟初始化 private static readonly Lazy instance = new Lazy(() => CreateInstanceOfT(), isThreadSafe: true); // 提供获取单例实例的静态属性 public static T Instance => instance.Value; // 保护的构造函数,防止直接实例化 protected Singleton() { // 在此处可以添加其他初始化逻辑 } // 创建T类型的实例 private static T CreateInstanceOfT() { return Activator.CreateInstance(typeof(T), true) as T; } } /*示例 internal class MySingletonClass : Singleton { // 在此处可以添加其他成员或方法 private MySingletonClass() { // 在此处可以添加初始化逻辑 } } internal class Test { private void Method() { // 使用单例实例 MySingletonClass instance1 = MySingletonClass.Instance; MySingletonClass instance2 = MySingletonClass.Instance; // 验证是否为同一实例 Console.WriteLine($"instance1 == instance2: {instance1 == instance2}"); // 可以在这里添加其他业务逻辑... } } */ }