静态内部类实现
package com.haxianhe.singleton;
/**
* 静态内部类
*/
public class Singleton5 {
private Singleton5() {
}
private static class InstanceFactory {
public static Singleton5 instance = new Singleton5();
}
public static Singleton5 getInstance() {
return InstanceFactory.instance;
}
}
饿汉模式
package com.haxianhe.singleton;
/**
* 饿汉模式
* */
public class Singleton4 {
private Singleton4() {
}
private static Singleton4 instance = new Singleton4();
public static Singleton4 getInstance() {
return instance;
}
}
懒汉模式(双重锁检测)
package com.haxianhe.singleton;
/**
* 双重锁检测(懒汉模式)
*/
public class Singleton3 {
private Singleton3() {
}
private static Singleton3 instance = null;
public static Singleton3 getInstance() {
if (instance == null) {
synchronized (instance) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}