1、单例模式之饿汉模式
package com.day2;
public class SingletonPattern {
private static final SingletonPattern singletonPattern
= new SingletonPattern();
private SingletonPattern() {
}
public static SingletonPattern getInstance() {
return singletonPattern;
}
}
优点:线程出现以前就初始化,不存在线程访问安全问题。没有加任何锁,执行效率高,用户体验比懒汉模式更好
缺点:类加载时就初始化,不管用与不用都占用空间,浪费内存
结论:适用于单例对象较少的情况
2、单例模式之懒汉单例模式
package com.day2;
public class SingletonPattern {
private SingletonPattern() {
}
private static SingletonPattern singletonPattern = null;
public static SingletonPattern getInstance() {
if (singletonPattern == null) {
singletonPattern = new SingletonPattern();
}
return singletonPattern;
}
}
结论:该方式线程不安全,但效率高,适用与单线程
package com.day2;
public class SingletonPattern {
private SingletonPattern() {
}
private static SingletonPattern singletonPattern = null;
public synchronized static SingletonPattern getInstance() {
if (singletonPattern == null) {
singletonPattern = new SingletonPattern();
}
return singletonPattern;
}
}
结论:该方式线程安全,但效率低
package com.day2;
public class SingletonPattern {
private SingletonPattern() {
}
private static SingletonPattern singletonPattern = null;
public static SingletonPattern getInstance() {
//双重检查锁初步优化
if (singletonPattern == null) {
synchronized (SingletonPattern.class){
if (singletonPattern==null){
singletonPattern = new SingletonPattern();
}
}
}
return singletonPattern;
}
}
package com.day2;
public class SingletonPattern {
private SingletonPattern() {
}
public static final SingletonPattern getInstance() {
return LazySingletonPattern.LAZY;
}
//静态内部类进一步优化
private static class LazySingletonPattern {
private static final SingletonPattern LAZY = new SingletonPattern();
}
}
package com.day2;
public class SingletonPattern {
private SingletonPattern() {
//防止反序列化创建多个实例
if (LazySingletonPattern.LAZY != null) {
throw new RuntimeException("不允许创建多个实例");
}
}
public static final SingletonPattern getInstance() {
return LazySingletonPattern.LAZY;
}
private static class LazySingletonPattern {
private static final SingletonPattern LAZY = new SingletonPattern();
}
}
结论:上面反序列化可以破坏单例,以上单例模式,兼顾性能,内存,线程安全
package com.day2;
public class SingletonPattern {
private SingletonPattern() {
//防止反序列化创建多个实例
if (LazySingletonPattern.LAZY != null) {
throw new RuntimeException("不允许创建多个实例");
}
}
public static final SingletonPattern getInstance() {
return LazySingletonPattern.LAZY;
}
private static class LazySingletonPattern {
private static final SingletonPattern LAZY = new SingletonPattern();
}
private Object readResolve(){
return LazySingletonPattern.LAZY;
}
}
结论:上面反序列化不可以破坏单例,以上单例模式,兼顾性能,内存,线程安全。。。
----枚举方式单例、容器方式单例和线程方式单例(ThreadLocal)后续补充----