
public class HungryManDemo {
private static final HungryManDemo instance = new HungryManDemo();
private HungryManDemo() {}
public static HungryManDemo getInstance(){
return instance;
}
}
public class LazyManDemo {
private static LazyManDemo instance;
private LazyManDemo() {}
public static LazyManDemo getInstance() {
if (instance == null) {
instance = new LazyManDemo();
}
return instance;
}
}volatile,禁止指令重排序
volatile修饰的变量,以提升性能

public class LazyManDoubleCheckDemo {
private static volatile LazyManDoubleCheckDemo instance;
private LazyManDoubleCheckDemo() {}
public static LazyManDoubleCheckDemo getInstance() {
LazyManDoubleCheckDemo temp = instance;
if (temp == null) {
synchronized (LazyManDoubleCheckDemo.class) {
temp = instance;
if (temp == null) {
temp = new LazyManDoubleCheckDemo();
instance = temp;
}
}
}
return instance;
}
}
public class StaticInnerClassDemo {
private StaticInnerClassDemo() {}
private static class SingletonHolder{
private static final StaticInnerClassDemo instance = new StaticInnerClassDemo();
}
public static StaticInnerClassDemo getInstance() {
return SingletonHolder.instance;
}
}
public enum EnumDemo {
INSTANCE;
}反序列化会产生新对象,违反单例规则
解决方案:JVM从内存中反序列化地"组装"一个新对象时,会自动调用类的readResolve方法,我们可以通过此方法返回指定好的对象。

public class SerialProblem {
private static volatile SerialProblem instance;
private SerialProblem() {}
public static SerialProblem getInstance() {
SerialProblem temp = instance;
if (temp == null) {
synchronized (SerialProblem.class) {
temp = instance;
if (temp == null) {
temp = new SerialProblem();
instance = temp;
}
}
}
return instance;
}
private Object readResolve() {
return instance;
}
}反射获取构造器,进行实例化产生新对象
解决方案:第二次实例化的时候,抛出异常

public class ReflectProblem {
private static volatile ReflectProblem instance;
private ReflectProblem() {
Assert.isNull(instance);
}
public static ReflectProblem getInstance() {
ReflectProblem temp = instance;
if (temp == null) {
synchronized (ReflectProblem.class) {
temp = instance;
if (temp == null) {
temp = new ReflectProblem();
instance = temp;
}
}
}
return instance;
}
}