首页 > 代码库 > Design Patterns 乌蒙山连着山外山---单件模式singleton pattern

Design Patterns 乌蒙山连着山外山---单件模式singleton pattern

 1     //包含单件实例的类Singleton 2     public class Singleton 3     { 4         //声明用于存储单件实例的变量instance 5         private static Singleton instance; 6         //定义用于标识同步线程的对象locker 7         private static Object locker = new Object(); 8         //私有的构造函数Singleton 9         private Singleton() { }10         //公共访问的返回单件实例的函数GetInstance11         public static Singleton GetInstance()12         {13             //第一重“锁”只为了提高些性能14             if (instance == null)15             {16                 //线程锁定块17                 lock (locker)18                 {19                     //第二重“锁”防止多线程多次new实例20                     if (instance == null)21                     {22                         //new唯一实例23                         instance = new Singleton();24                     }25                 }26             }27             //返回单件实例28             return instance;29         }30     }