Edmund's zone

导航

< 2025年4月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 1 2 3
4 5 6 7 8 9 10

统计

单例模式(Singleton)

最近用到了单例模式。在这里做个总结,整理思路。

使用情形:在调用form时,可能出现此form已经被初始化了,但是调用者并不知道,重新new了一个新的form,导致调用者的混乱。使用了singleton模式,做到了在内存中只有一个form,避免多次new。

 

复制代码
Form's Singleton
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一直在内存中存在。

posted on   Edmund Li  阅读(319)  评论(0编辑  收藏  举报

编辑推荐:
· 一文彻底搞懂 MCP:AI 大模型的标准化工具箱
· 电商平台中订单未支付过期如何实现自动关单?
· 用 .NET NativeAOT 构建完全 distroless 的静态链接应用
· 为什么构造函数需要尽可能的简单
· 探秘 MySQL 索引底层原理,解锁数据库优化的关键密码(下)
阅读排行:
· 短信接口被刷爆:我用Nginx临时止血
· .NET 平台上的开源模型训练与推理进展
· Google发布A2A开源协议:“MCP+A2A”成未来标配?
· C# 多项目打包时如何将项目引用转为包依赖
· 一款让 Everything 更加如虎添翼的 .NET 开源辅助工具!
点击右上角即可分享
微信分享提示