经常要用到Singleton模式,通常情况下我们是为那个类写一个static method来创建对象。.net3.5下,可以封装这么一个辅助类,
看代码如下:
1 #region Singleton
2 /// <summary>
3 /// Used for classes that are single instances per appdomain
4 /// </summary>
5 public static class Singleton
6 {
7 private static class Storage<T>
8 {
9 internal static T s_instance;
10 }
11
12 /// <summary>
13 /// Gets the instance.
14 /// </summary>
15 /// <typeparam name="T">Func<T></typeparam>
16 /// <param name="op">The op.</param>
17 /// <returns>T</returns>
18 /// <remark>Author : PetterLiu 2008-12-2816:02 http://wintersun.cnblogs.com </remark>
19 public static T GetInstance<T>(Func<T> op)
20 {
21 if (Storage<T>.s_instance == null)
22 {
23 lock (typeof(Storage<T>))
24 {
25 if (Storage<T>.s_instance == null)
26 {
27 T temp = op();
28 System.Threading.Thread.MemoryBarrier();
29 Storage<T>.s_instance = temp;
30 }
31 }
32 }
33 return Storage<T>.s_instance;
34 }
35
36 /// <summary>
37 /// Gets the instance.
38 /// </summary>
39 /// <typeparam name="T">T</typeparam>
40 /// <returns>T</returns>
41 /// <remark>Author : PetterLiu 2008-12-2816:02 http://wintersun.cnblogs.com </remark>
42 public static T GetInstance<T>()
43 where T : new()
44 {
45 return GetInstance(() => new T());
46 }
47 }
48 #endregion
2 /// <summary>
3 /// Used for classes that are single instances per appdomain
4 /// </summary>
5 public static class Singleton
6 {
7 private static class Storage<T>
8 {
9 internal static T s_instance;
10 }
11
12 /// <summary>
13 /// Gets the instance.
14 /// </summary>
15 /// <typeparam name="T">Func<T></typeparam>
16 /// <param name="op">The op.</param>
17 /// <returns>T</returns>
18 /// <remark>Author : PetterLiu 2008-12-2816:02 http://wintersun.cnblogs.com </remark>
19 public static T GetInstance<T>(Func<T> op)
20 {
21 if (Storage<T>.s_instance == null)
22 {
23 lock (typeof(Storage<T>))
24 {
25 if (Storage<T>.s_instance == null)
26 {
27 T temp = op();
28 System.Threading.Thread.MemoryBarrier();
29 Storage<T>.s_instance = temp;
30 }
31 }
32 }
33 return Storage<T>.s_instance;
34 }
35
36 /// <summary>
37 /// Gets the instance.
38 /// </summary>
39 /// <typeparam name="T">T</typeparam>
40 /// <returns>T</returns>
41 /// <remark>Author : PetterLiu 2008-12-2816:02 http://wintersun.cnblogs.com </remark>
42 public static T GetInstance<T>()
43 where T : new()
44 {
45 return GetInstance(() => new T());
46 }
47 }
48 #endregion
UnitTest:

http://wintersun.cnblogs.com
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· .NET 使用 DeepSeek R1 开发智能 AI 客户端
· 10亿数据,如何做迁移?
· 推荐几款开源且免费的 .NET MAUI 组件库
· c# 半导体/led行业 晶圆片WaferMap实现 map图实现入门篇
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!