懒汉式
package com.qf.singleton;
//懒汉式
//只有用的时候才声明 分配空间
public class LazySingleton {
//构造器私有化
private LazySingleton() {
}
//声明对象
private static LazySingleton lazySingleton = null;
//提供方法让外部获取对象
//实例化方法 线程安全
public static synchronized LazySingleton getLazySingleton() {
if (null == lazySingleton) {
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
饿汉式
package com.qf.singleton;
//饿汉式
public class HungrySingleton {
//构造器私有化
private HungrySingleton() {
}
//声明对象
private static HungrySingleton hungrySingleton = null;
//提供方法让外部获取对象
//实例化方法 线程安全
public static synchronized HungrySingleton getHungrySingleton() {
return hungrySingleton = new HungrySingleton();
}
}
双重检查锁
package com.qf.singleton;
//双重锁单例
public class LockSingleton {
//构造器私有化
private LockSingleton() {
}
//声明对象
private static LockSingleton lockSingleton = null;
//提供方法让外部获取对象
//实例化方法 线程安全
//实例化方法
public static LockSingleton getLockSingleton() {
//先检查当前实例是否为空,如果不存在再进行同步
if (null == lockSingleton) {
//同步
synchronized (LockSingleton.class) {
//再次检查当前实例是否为空
if (null == lockSingleton) {
//返回
lockSingleton = new LockSingleton();
}
}
}
return lockSingleton;
}
}



