常见模式
/**
*
* @author zhangzhen
*/
public class Singleton {
// 私有构造器
private Singleton() {
}
private static final Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
}
问题:使用没使用都会产生实例
懒汉模式
/**
*
* @author zhangzhen
*/
public class Singleton2 {
// 私有化构造器
private Singleton2() {
}
private static Singleton2 INSTANCE;
public static Singleton2 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton2();
}
return INSTANCE;
}
}
问题:存在线程问题,解决思路加锁
/**
*
* @author zhangzhen
*/
public class Singleton2 {
// 私有化构造器
private Singleton2() {
}
private static Singleton2 INSTANCE;
public static Singleton2 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton2.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton2();
}
}
}
return INSTANCE;
}
}
问题:由于加锁性能会下降
静态内部类模式
/**
* 静态内部类模式 <br>
* JVM 保证单例
* 并且加载时不会实例化
* @author zhangzhen
*/
public class Singleton4 {
private Singleton4() {
}
private static class Singleton5 {
private final static Singleton4 INSTANCE = new Singleton4();
}
public static Singleton4 getInstance() {
return Singleton5.INSTANCE;
}
}
大神模式
/**
* 解决线程问题,并反序列化
*
* @author zhangzhen
*/
public enum Singleton3 {
INSTANCE;
}
问题:看着别扭,不是类
网友评论