单例模式注意事项
1、静态化私有变量
2、私有化构造函数
3、公共静态的构造方法
几个例子:
/**=============================== 单例懒汉模式,用到时才加载 =============================================*/ // private static SingleMode instance ; // private SingleMode(){} // // /** // * 单例懒汉模式,用到时才加载 // * @return // */ // public static SingleMode getInstance(){ // if (null==instance){ // instance = new SingleMode(); // } // return instance; // } /** * =============================== 单例饿汉模式,不等用到时就加载 ============================================= */ // private static SingleMode instance = new SingleMode(); // // private SingleMode() { // } // // public static SingleMode getInstance() { // return instance; // } /** * =============================== 多线程操作 注意线程安全 ============================================================ */ private static SingleMode instance; private SingleMode() { } public static SingleMode getInstance() { synchronized (instance) { if (null == instance) { instance = new SingleMode(); } } return instance; }