public class Singleton {
public static void main(String[] args) {
System.out.println(Singleton1.getInstance() == Singleton1.getInstance());
System.out.println(Singleton2.getInstance() == Singleton2.getInstance());
System.out.println(Singleton3.getInstance() == Singleton3.getInstance());
System.out.println(Singleton4.getInstance() == Singleton4.getInstance());
System.out.println(Singleton5.getInstance() == Singleton5.getInstance());
System.out.println(Singleton6.getInstance() == Singleton6.getInstance());
System.out.println(Singleton7.getInstance() == Singleton7.getInstance());
System.out.println(Singleton8.SINGLETON_8 == Singleton8.SINGLETON_8);
}
}
/**
* @description: 饿汉式 (final修饰提前加载实例化)内存浪费
*/
class Singleton1 {
private Singleton1() {
}
private final static Singleton1 singleton = new Singleton1();
public static Singleton1 getInstance() {
return singleton;
}
}
/**
* @description: 饿汉式 (在代码块提前加载实例化)内存浪费
*/
class Singleton2 {
private Singleton2() {
}
private static Singleton2 singleton;
static {
singleton = new Singleton2();
}
public static Singleton2 getInstance() {
return singleton;
}
}
/**
* @description: 懒汉式, 检查对象是否为空才创建对象 (试用与单线程)
*/
class Singleton3 {
private Singleton3() {
}
private static Singleton3 singleton;
public static Singleton3 getInstance() {
if (singleton == null) {
return singleton = new Singleton3();
}
return singleton;
}
}
/**
* @description: 懒汉式, 检查对象是否为空才创建对象(试用与多线程),同步方法
*/
class Singleton4 {
private Singleton4() {
}
private static Singleton4 singleton;
public synchronized static Singleton4 getInstance() {
if (singleton == null) {
return singleton = new Singleton4();
}
return singleton;
}
}
/**
* @description: 懒汉式, 检查对象是否为空才创建对象(试用与多线程),同步代码块
*/
class Singleton5 {
private Singleton5() {
}
private static Singleton5 singleton;
public static Singleton5 getInstance() {
if (singleton == null) {
synchronized (Singleton5.class) {
return singleton = new Singleton5();
}
}
return singleton;
}
}
/**
* @description: 懒汉式, 检查对象是否为空才创建对象(试用与多线程),同步代码块 双重检查
*/
class Singleton6 {
private Singleton6() {
}
private static volatile Singleton6 singleton;
public static Singleton6 getInstance() {
if (singleton == null) {
synchronized (Singleton6.class) {
if (singleton == null) {
return singleton = new Singleton6();
}
}
}
return singleton;
}
}
/**
* @description: 类加载方式, 静态内部类
*/
class Singleton7 {
private Singleton7() {
}
static class Singleton7Static {
private static Singleton7 singleton = new Singleton7();
}
public static Singleton7 getInstance() {
return Singleton7Static.singleton;
}
}
enum Singleton8 {
SINGLETON_8
}
强烈推荐使用第6种写法双重检查解决多线程安全问题