Java 设计模式之单例模式

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。

这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

注意:

  • 单例类只能有一个实例
  • 单例类必须自己创建自己的唯一实例
  • 单例类必须给所有其他对象提供这一实例

实现

从具体的实现角度来说就是以下三点:

  1. 单例模式的类只提供私有的构造函数
  2. 类定义中含有一个该类的静态私有对象
  3. 该类提供了一个静态的公有的函数用于创建或获取它本身的静态私有对象

下面是单例模式的几种常见写法:

1、懒汉式(单线程)

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton {

private static Singleton instance;

private Singleton() {}

public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

优点:延迟加载。

缺点:这种写法只适用于单线程,如果在多线程下可能会产生多个实例。


下面介绍的几种方式都支持多线程但在性能上有所差异

2、懒汉式(多线程)

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Singleton {

private static Singleton instance;

private Singleton() {}

public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

优点:第一次调用才初始化,避免内存浪费。

缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。

3、饿汉式

1
2
3
4
5
6
7
8
9
10
public class Singleton {

private final static Singleton INSTANCE = new Singleton();

private Singleton(){}

public static Singleton getInstance() {
return INSTANCE;
}
}

优点:写法简单,没有加锁,执行效率会提高。

缺点:如果从始至终未使用过这个实例,则会造成资源的浪费。

4、双重检查(推荐用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Singleton {

private static volatile Singleton instance;

private Singleton() {}

public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

优点:线程安全,延迟加载,效率高。

5、静态内部类(推荐用)

1
2
3
4
5
6
7
8
9
10
11
12
public class Singleton {

private Singleton() {}

private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}

这种方式类似于饿汉式,但又有不同。这种方式同样利用了 Classloader 机制来保证初始化 instance 时只有一个线程 ,不同的是饿汉式只要 Singleton 类被装载就会实例化,不会延迟加载,而静态内部类在 Singleton 类被装载时不会立即实例化,而是在调用 getInstance() 方法时才会装载 SingletonInstance 这个内部类完成 Singleton 的实例化。

优点:线程安全,延迟加载,效率高。

6、枚举(推荐用)

1
2
3
4
5
public enum Singleton {
INSTANCE;
public void whateverMethod() {
}
}

这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化,也不能通过 reflection attack 来调用私有构造方法。这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。不过,由于 JDK1.5 之后才加入 enum 特性,用这种方式写不免让人感觉生疏,在实际工作中,也很少用。

总结

一般情况下,不建议使用第 1 种和第 2 种懒汉方式,建议使用第 3 种饿汉方式。只有在要明确实现 lazy loading 效果时,才会使用第 5 种静态内部类的方式。如果涉及到反序列化创建对象时,可以尝试使用第 6 种枚举方式。如果有其他特殊的需求,可以考虑使用第 4 种双重检查。