单例模式(Singleton)

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

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

 

ContractedBlock.gif ExpandedBlockStart.gif 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):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

 

 

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一直在内存中存在。

转载于:https://www.cnblogs.com/edmundli/archive/2011/01/09/singleton.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值