普通模式:判断是否为空,如果没有instance,就new 一个;

 1 public class Singleton
 2 {
 3     private static Singleton instance;
 4     private Singleton()
 5     {
 6     }
 7     public Singleton GetInstance()
 8     {
 9         if(instance == null)
10         {
11             instance = new Singleton();
12         }
13         return instance;
14     }            
15 }

 

懒汉模式:直接在编译时new一个实例;也可以解决多线程的问题;

 1 public class Singleton
 2 {
 3     private static readonly Singleton instance = new Singleton();
 4     private Singleton()
 5     {
 6     }
 7     public Singleton GetInstance()
 8     {
 9         return instance;
10     }            
11 }