Edmund's zone

导航

单例模式(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):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

 

 

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 2011-01-09 15:40  Edmund Li  阅读(315)  评论(0编辑  收藏  举报