主要介绍单例模式的一种写法、注意事项、作用、测试,以Java语言为例,下面代码是目前见过最好的写法:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Singleton {     private static volatile Singleton instance = null;     // private constructor suppresses     private Singleton(){     }     public static Singleton getInstance() {         // if already inited, no need to get lock everytime         if (instance == null) {             synchronized (Singleton.class) {                 if (instance == null) {                     instance = new Singleton();                 }             }         }         return instance;     } } | 
1、需要注意的点
其中需要注意的点主要有三点
(1) 私有化构造函数
(2) 定义静态的Singleton insta[......]