创建单例3步骤
1、构造函数私有化
2、持有该类的私有化静态对象
3、获取单例的静态方法
饿汉模式
public class EHam {
private static EHam eHam = new EHam();
private EHam(){};
public static EHam getInstance(){
return eHam;
}
}
懒汉模式
- 非线程安全 【错误的XXX】
public class LHam {
private static LHam lHam = null;
private LHam(){
}
public static LHam getInstance(){
if (lHam == null ) {
lHam = new LHam();
}
return lHam;
}
}
- 安全模式
public class SafeLHam {
private static SafeLHam safeLHam = null;
private SafeLHam(){
}
public static synchronized SafeLHam getInstance(){
if ( safeLHam == null ){
safeLHam = new SafeLHam();
}
return safeLHam;
}
}
双检查锁
public class DoubleCheck {
private static DoubleCheck doubleCheck = null;
private DoubleCheck(){
}
public static DoubleCheck getInstance(){
if( doubleCheck == null ){
synchronized (DoubleCheck.class){
if ( doubleCheck == null )
doubleCheck = new DoubleCheck();
}
}
return doubleCheck;
}
}
内部静态类
public class SingleTon {
private static class SingleTonHolder{
private static final SingleTon INSTANCE = new SingleTon();
}
private SingleTon(){
}
public static SingleTon getInstance(){
return SingleTonHolder.INSTANCE;
}
}
枚举创建单例
实现方式通过Java 枚举类型本身的特性,保证了实例创建的线程安全性和实例的唯一性
/**
* 通过枚举创建单例,枚举本身就是单例的
*/
public enum IdGeneratorEnum {
INSTANCE;
private AtomicLong id = new AtomicLong(0);
public long getId() {
return id.incrementAndGet();
}
}