本章提供五种单例模式
一 饿汉式
类加载到内存后,就实例化一个单例,JVM保证线程安全 唯一缺点:不管用到与否,类装载时就完成实例化
public class SingletonModel1 {
private static final SingletonModel1 singletonModel1 = new SingletonModel1 ( ) ;
private SingletonModel1 ( ) { }
public static SingletonModel1 getSingletonModel1 ( ) {
return singletonModel1;
}
}
二 懒汉式
项目启动时不加载,只有在调用的时候才加载 锁加在方法上,效率略低
public class SingletonModel2 {
private static SingletonModel2 singletoModel2 = null;
private SingletonModel2 ( ) { }
public static synchronized SingletonModel2 getSingletoModel2 ( ) {
if ( singletoModel2 == null) {
singletoModel2 = new SingletonModel2 ( ) ;
}
return singletoModel2;
}
}
三 懒汉式–CAS
锁不加在方法上,提高性能 采用CAS方法保证线程安全 采用volatile 保证 多线程可见 和 指令不会重排序,
public class SingletonModel3 {
private static volatile SingletonModel3 singletonModel3 = null;
private SingletonModel3 ( ) {
}
public static SingletonModel3 getSingletoModel3 ( ) {
if ( singletonModel3 == null) {
synchronized ( SingletonModel3. class ) {
if ( singletonModel3 == null) {
singletonModel3 = new SingletonModel3 ( ) ;
}
}
}
return singletonModel3;
}
}
四 内部类
静态内部类 加载外部类时不会加载内部类,这样可以实现懒加载 JVM保证单例
public class SingletonModel4 {
private SingletonModel4 ( ) {
}
private static class singletonHolder {
private final static SingletonModel4 singletonModel4 = new SingletonModel4 ( ) ;
}
public static SingletonModel4 getSingletoModel4 ( ) {
return singletonHolder. singletonModel4;
}
}
五 枚举
枚举方式 不仅可以解决线程同步,还可以防止反序列化。
public enum SingletonEnum5 {
SINGLETON;
}