//单例饿汉
public class Singleton01 {
private static final Singleton01 INSTANCE = new Singleton01();
private Singleton01() {
}
public static Singleton01 getInstance() {
return INSTANCE;
}
}
public class Singleton02 {
private volatile static Singleton02 INSTANCE;
//为什么要使用volatile
//执行构造方法和赋值的操作可能会指令重排序,并发情况下可能有两个对象被初始化
//故使用volatile,禁止指令重排序,保证线程安全
private Singleton02() {}
public static Singleton02 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton02.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton02();
}
}
}
return INSTANCE;
}
}
public class Singleton03 {
private Singleton03() {
}
//静态内部类自带懒加载
private static class SingletonHolder {
private static Singleton03 INSTANCE = new Singleton03();
}
public static Singleton03 getInstance() {
return SingletonHolder.INSTANCE;
}
}
public enum Singleton04 {
//枚举
INSTANCE;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。