定义
一个类至多有一个对象实例。这个实例被称为单例。在使用时才初始化被称为懒汉式单例,类一加载就初始化被叫做饿汉式单例。有8种常见实现方式。
实现
- 静态常量法:可用
public class Singleton {
private final static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
- 静态代码块:可用
public class Singleton {
private static Singleton instance;
static { instance = new Singleton(); }
private Singleton() {}
public Singleton getInstance() {
return instance;
}
}
- 静态方法:不可用
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
线程A进入第7句但还未来得及初始化时,线程B在第5句判断为null,所以也可以进入第6句,有并发问题。
- 同步方法:可用但不推荐
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (singleton == null)
singleton = new Singleton();
return singleton;
}
}
- 同步代码块:不可用
public class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
singleton = new Singleton();
}
}
return singleton;
}
}
线程A进入第7句但还未来得及初始化时,线程B在第5句判断为null,虽然得等到A初始化完成,但也可以进入第7句,有并发问题。
- 双重检查:可用且推荐用
public class Singleton {
private static volatile Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
- 静态内部类:可用且推荐用
public class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
- 枚举:可用且推荐用
public enum Singleton {
INSTANCE;
public void whateverMethod() {
doSomethingHere...
}
}
网友评论