C# 单例推荐方式

参考:Implementing the Singleton Pattern in C#

使用场景:

1. 要求生产唯一序列号;
2. WEB 中的计数器,不用每次刷新都在数据库里加一次,用单例先缓存起来;
3. 创建的一个对象需要消耗的资源过多,比如 I/O 与数据库的连接等;
4. 全局配置文件访问类,单例来保证唯一性;
5. 日志记录帮助类,全局一个实例一般就够了;
6. 桌面应用常常要求只能打开一个程序实例或一个窗口。

使用方式:

not quite as lazy, but thread-safe without using locks

 1     public sealed class Singleton
 2     {
 3         private static readonly Singleton instance = new Singleton();
 4 
 5         // Explicit static constructor to tell C# compiler
 6         // not to mark type as beforefieldinit
 7         static Singleton()
 8         {
 9         }
10 
11         private Singleton()
12         {
13         }
14 
15         public static Singleton Instance
16         {
17             get
18             {
19                 return instance;
20             }
21         }
22     }

using .NET 4's Lazy<T> type

 1     public sealed class Singleton
 2     {
 3         private static readonly Lazy<Singleton>
 4             lazy =
 5                 new Lazy<Singleton>
 6                     (() => new Singleton());
 7 
 8         public static Singleton Instance { get { return lazy.Value; } }
 9 
10         private Singleton()
11         {
12         }
13     }

如下地址有翻译原文:

https://www.cnblogs.com/leolion/p/10241822.html

猜你喜欢

转载自www.cnblogs.com/YourDirection/p/12909627.html