单例模式的特点:
- 一个类只能有一个实例
- 类自己创建这个实例
- 整个系统都共同使用这个实例
单例模式分为:
- 懒汉式:类一加载就创建对象,上来就new一个不可修改的类对象,再来一个空的私有构造方法,和一个公有的入口(返回值是类对象)
- 饿汉式:用的时候,才去创建对象,声明一个为空的对象,在调用时new一个新的对象
以上两种情况在多线程下是不安全的,因为new对象是非原子性的,重排序问题会造成多线程下不安全
1.饿汉模式
class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2.懒汉模式-单线程版
class Singleton {
private static Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
3.懒汉模式-多线程版-性能低
class Singleton {
private static Singleton instance = null;
private Singleton() {}
public synchronized static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
4.懒汉模式-多线程版-二次判断-性能高
class Singleton {
private static volatile Singleton instance = null;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}