2025-10-11 18:25:59 +08:00

111 lines
3.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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