Java单例模式几种写法
1、饿汉式(最常见写法,推荐写法)
- 第一种写法
public class Singleton1 {
private static final Singleton1 INSTANCE = new Singleton1();
private Singleton1() {
}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
- 第二种写法
public class Singleton1 {
private static final Singleton1 INSTANCE;
static {
INSTANCE = new Singleton1();
}
private Singleton1() {
}
public static Singleton1 getInstance() {
return INSTANCE;
}
}
2、懒汉式(线程不安全)
- 在多线程下会导致new出来的不是同一个实例
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 INSTANCE;
public Singleton2 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton2();
}
return INSTANCE;
}
}
- 加锁方式(影响性能)
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 INSTANCE;
public synchronized Singleton2 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton2();
}
return INSTANCE;
}
}
- 通过减少同步代码块加锁(多线程下也会导致不是同一个实例)
ublic class Singleton2 {
private Singleton2() {
}
private static Singleton2 INSTANCE;
public Singleton2 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton2.class) {
INSTANCE = new Singleton2();
}
}
return INSTANCE;
}
}
- 双重检查
public class Singleton2 {
private Singleton2() {
}
private static Singleton2 INSTANCE;
public Singleton2 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton2.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton2();
}
}
}
return INSTANCE;
}
}
3. 内部类方式
- 通过定义一个内部类的方式调用,运用了类加载机制,保证线程安全
public class Singleton2 {
private Singleton2() {
}
public static class Singleton2Holder {
private Singleton2Holder() {
}
private static final Singleton2 INSTANCE = new Singleton2();
}
public static Singleton2 getInstance() {
return Singleton2Holder.INSTANCE;
}
}
4. 枚举方式(推荐写法)
public enum Singleton {
INSTANCE;
public void test() {
}
public static void main(String[] args) {
Singleton.INSTANCE.test();
}
}