Java单例模式
单例模式线程安全的四种创建方式
静态代码块,静态内部类,双重检锁,枚举模式
代码展示
静态代码块
private static final SingletonDemo SINGLETON_DEMO;
static {
SINGLETON_DEMO = new SingletonDemo();
}
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
return SINGLETON_DEMO ;
}
静态内部类
private singletonDemo(){
}
public static singletonDemo getInstance(){
return Inner.singletonDemo;
}
public static class Inner {
private static singletonDemo singletonDemo = new singletonDemo() ;
}
双重检锁
private static volatile SingletonDemo singletonDemo = null ;
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
try {
Thread.sleep(5000);
}catch(InterruptedException e) {
throw new RuntimeException(e);
}
//双重校验锁 保证线程安全
if(singletonDemo==null){
synchronized(SingletonDemo.class){
if(singletonDemo==null){
singletonDemo = new SingletonDemo();
}
}
}
return singletonDemo ;
}
枚举模式
private SingletonDemo(){
}
public static SingletonDemo getInstance(){
return InnerEnum.INNER_ENUM.getInstance();
}
private static enum InnerEnum {
INNER_ENUM;
private final SingletonDemo singletonDemo ;
private InnerEnum(){
singletonDemo = new SingletonDemo() ;
}
private SingletonDemo getInstance(){
return singletonDemo;
}
}