public class singleton { /** * 预先实例化好了,也可以使用懒实例化,在构造函数中实例化,不过要注意线程同步的位码头 */ private static singleton singleton = new singleton(); /** * 私有构造函数 */ private singleton() { } /** * 对外接口 * @return */ public static singleton getinstance() { return singleton; }}
例子2 懒实例化的单例模式
/** * 使用懒加载方式 */public class singleton2 { private static singleton2 singleton2 = null; private singleton2() { } /** * 缺点是每次都要判断是否为null,而且同步浪费效率 */ public synchronized static singleton2 getinstance() { if (singleton2 == null) { singleton2 = new singleton2(); } return singleton2; }}
例子3 双重成例检查的单例模式
/** * 使用双重成例检查的单例模式 */public class singleton3 { private static singleton3 singleton3 = null; private singleton3() { } /** * 只会判断一次null,效率高了,但是代码稍微复杂了一点 */ public static singleton3 getinstance() { if (singleton3 == null) { synchronized (singleton3.class) { if (singleton3 == null) { singleton3 = new singleton3(); } } } return singleton3; } }