单例模式(Singleton)
最近用到了单例模式。在这里做个总结,整理思路。
使用情形:在调用form时,可能出现此form已经被初始化了,但是调用者并不知道,重新new了一个新的form,导致调用者的混乱。使用了singleton模式,做到了在内存中只有一个form,避免多次new。

1 public partial class ClientForm : Form
2 {
3 private static ClientForm clientForm = null;
4
5 private ClientForm()
6 {
7 InitializeComponent();
8 }
9
10 public ClientForm GetInstance()
11 {
12 if(clientForm == null)
13 {
14 clientForm = new ClientForm();
15 }
16
17 return clientForm;
18 }
19 }
20
下面介绍一下通用的情形:
单例模式(singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Singleton { private static Singleton instance; private Singleton() { } public Singleton GetInstance() { if (instance == null ) { instance = new Singleton(); } return instance; } } |
简单的说,单例模式是对唯一实例的受控访问。
下面是在多线程时的单例模式示例代码:
1 class Singleton
2 {
3 private static Singleton instance;
4 private static readonly object syncRoot = new object();
5
6 private Singleton()
7 {
8 }
9
10 public Singleton GetInstance()
11 {
12 if(instance == null)
13 {
14 lock(syncRoot)
15 {
16 if(instance == null)
17 {
18 instance = new Singleton();
19 }
20 }
21 }
22
23 return instance;
24 }
25 }
26
对于多线程的实现,在实际中还有采用静态初始化的方式,代码如下:
1 public sealed class Singleton//avoid inherited class
2 {
3 //create instance when calls the class for the first
4 //time.
5 private static readonly Singleton instance = new Singleton();
6 private Singleton()
7 {
8 }
9
10 public static Singleton GetInstance()
11 {
12 return instance;
13 }
14 }
15
当需要释放此instance或者form时,须要调用instance=null来实现。否则此instance一直在内存中存在。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
· 短信接口被刷爆:我用Nginx临时止血
· .NET 平台上的开源模型训练与推理进展
· Google发布A2A开源协议:“MCP+A2A”成未来标配?
· C# 多项目打包时如何将项目引用转为包依赖
· 一款让 Everything 更加如虎添翼的 .NET 开源辅助工具!